LeetCode 243. Shortest Word Distance (最短单词距离)$

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 都被找到的情况下,记录它们的距离

 

 1 public class Solution 
 2 {
 3     public int shortestDistance(String[] words, String word1, String word2) 
 4     {
 5         int p1 = -1, p2 = -1, min = Integer.MAX_VALUE;
 6         
 7         for(int i=0; i<words.length; i++)
 8         {
 9             if(words[i].equals(word1)) // if find word1, mark its position
10                 p1 = i;    
11             else if(words[i].equals(word2)) // if find word2, mark its position
12                 p2 = i;
13             
14             if(p1 != -1 && p2 != -1) // if find word1 and word2, save the smaller distance
15                 min = Math.min(min, Math.abs(p1 - p2));
16         }
17         
18         return min;
19     }
20 }

 

参考资料:

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

 

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

 

posted @ 2017-09-09 03:35  Jimmy_Cheng  阅读(296)  评论(0编辑  收藏  举报