您的位置:首页 > 其它

LeetCode 245. Shortest Word Distance III (最短单词距离之三) $

2017-09-09 05:01 411 查看

This is a follow up of Shortest Word Distance. The only difference is now word1 could be the same as word2.

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

word1 and word2 may be the same and they represent two individual words in the list.

For example,
Assume that words = 

["practice", "makes", "perfect", "coding", "makes"]
.

Given word1 = 

“makes”
, word2 = 
“coding”
, return 1.
Given word1 = 
"makes"
, word2 = 
"makes"
, return 3.

Note:
You may assume word1 and word2 are both in the list.

 

题目标签:Array

  题目给了我们一个words array, word1 和word2, 让我们找到word1 和word2 之间最小距离。相比于 243. Shortest Word Distance, 这一题的区别就是,两个word 可能会相等。在243 code的基础上,稍微改一下就可以了。

  因为如果当两个word 是相等的话,那么 不管出现的是word1 还是word2,  在比较words[i] 与 word1 的时候 都会是true,所以只要在这个情况里面 多加一个条件 -> 当 两个word 相等,并且 当前word 是至少第二个word1 的时候,记录它们的距离。

  因为永远到不了else if, 所以p2 永远是 -1, 那么最后一个if 也永远不会进入。

  当两个word 不相等的话,就和243题一样,具体看code。

 

  一直想问,那么这一题的 之二 去哪里了?  怎么只有1 和3 呢?

 

Java Solution:

Runtime beats 46.30% 

完成日期:09/08/2017

关键词:Array

关键点:当两个word相同时候,进入特别条件

 

class Solution
{
public int shortestWordDistance(String[] words, String word1, String word2)
{
int p1 = -1, p2 = -1, min = Integer.MAX_VALUE;
boolean same = word1.equals(word2);

for(int i=0; i<words.length; i++)
{
if(words[i].equals(word1)) // if find word1, mark its position
{
if(same && p1 != -1) // if two words are same and found a word before
min = Math.min(min, Math.abs(i - p1));

p1 = i;
}
else if(words[i].equals(word2)) // if find word2, mark its position
p2 = i;

if(p1 != -1 && p2 != -1) // if find word1 and word2, save the smaller distance
min = Math.min(min, Math.abs(p1 - p2));
}

return min;
}
}

参考资料:N/A

 

LeetCode 算法题目列表 - LeetCode Algorithms Questions List

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: