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

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

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

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


题目标签:Array

  题目给了我们一个words array, word1 和word2, 让我们找出word1 和word2 之间最短的距离。words array 里的word 可以重复出现。

  基本思想是:当找到任何一个word 的时候,记录它的 index, 当两个word 都确定被找到的时候,用它们的index 相减来记录它们之间的距离

Java Solution:

Runtime beats 52.07%

完成日期:04/27/2017

关键词:Array

关键点:当找到任何一个word 时候,记录它的index;只有当两个word 都被找到的情况下,记录它们的距离

 public class Solution
{
public int shortestDistance(String[] words, String word1, String word2)
{
int p1 = -1, p2 = -1, min = Integer.MAX_VALUE; for(int i=0; i<words.length; i++)
{
if(words[i].equals(word1)) // if find word1, mark its position
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;
}
}

参考资料:

https://discuss.leetcode.com/topic/20668/ac-java-clean-solution

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

04-15 13:10