问题描述:
Given an array of strings wordsDict and two different strings that already exist in the array word1 and word2, return the shortest distance between these two words in the list.
找两个元素在数组中的最短距离
思路:
用Hashmap记录相关元素(跳过不考虑不是word1或word2的)及其对应的出现位置,若此刻两个元素在map中都有,则我们计算它们的距离差的绝对值并与上一轮的值比较取较小者,这样遍历完整个数组,我们得到的距离就是最小距离。
关注限制条件:
Constraints:
1 <= wordsDict.length <= 3 * 104
1 <= wordsDict[i].length <= 10
wordsDict[i] consists of lowercase English letters.
word1 and word2 are in wordsDict.
word1 != word2
代码一遍过:
class Solution {
public int shortestDistance(String[] wordsDict, String word1, String word2) {
Map<String, Integer> map = new HashMap<>();
int minDist = Integer.MAX_VALUE;
for (int i=0; i<wordsDict.length; i++){
if ((wordsDict[i].equals(word1)) || (wordsDict[i].equals(word2))){
if (wordsDict[i].equals(word1)) map.put(word1, i);
else map.put(word2,i);
if (map.containsKey(word1) && map.containsKey(word2)){
minDist = Math.min(minDist, Math.abs(map.get(word1)-map.get(word2)));
}
}
}
return minDist;
}
}
时间复杂度: O(n)