码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode solution 243: Shortest Word Distance

时间:2019-12-26 09:31:42      阅读:87      评论:0      收藏:0      [点我收藏+]

标签:mat   nat   state   imp   tween   youtube   distance   span   bilibili   

 

Problem Statement 

Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list.

Example:

Assume that words = ["practice", "makes", "perfect", "coding", "makes"].

Input: word1 = “coding”, word2 = “practice”
Output: 3
Input: word1 = "makes", word2 = "coding"
Output: 1

Note:

You may assume that word1 does not equal to word2, and word1 and word2 are both in the list.

 Problem link

Video Tutorial

You can find the detailed video tutorial here

Thought Process

It is a bit confusing at first to be confused with the "Edit Distance" problem. However, there are duplicate words in the array, it‘s just a matter of finding the minimum distance between two words, where words could be found in multiple places in the array.

 

Brute force way (for each word, find the closest distance with the other word) would give you O(N^2) time complexity where N is the array size. An O(N) optimization would be having two indices for each word and keep updating the minimum distance. It is greedy because the closer the two elements are, the smaller the distance would be.

 

You can refer to Leetcode official solution for a detailed explanation.

Solutions

 1 public int shortestDistance(String[] words, String word1, String word2) {
 2     if (words == null || words.length == 0 || word1 == null || word2 == null || word1.equals(word2)) {
 3         return -1;
 4     }
 5     int minDistance = words.length;
 6 
 7     int wordIndex1 = -1;
 8     int wordIndex2 = -1;
 9 
10     for (int i = 0; i < words.length; i++) {
11         if (words[i].equals(word1)) {
12             wordIndex1 = i;
13             if (wordIndex2 != -1) {
14                 minDistance = Math.min(minDistance, Math.abs(wordIndex1 - wordIndex2));
15             }
16         }
17         if (words[i].equals(word2)) {
18             wordIndex2 = i;
19             if (wordIndex1 != -1) {
20                 minDistance = Math.min(minDistance, Math.abs(wordIndex1 - wordIndex2));
21             }
22         }
23     }
24 
25     return minDistance;
26 }

 

Implementation

Time Complexity: O(N) where N is the array size

Space Complexity: O(1) Constant space

 

References

Leetcode solution 243: Shortest Word Distance

标签:mat   nat   state   imp   tween   youtube   distance   span   bilibili   

原文地址:https://www.cnblogs.com/baozitraining/p/12100071.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!