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.
public class Solution {
public int shortestDistance(String[] words, String word1, String word2) {
HashMap<String, List<Integer>> map = new HashMap<String, List<Integer>>();
for (int i = 0; i < words.length; i++) {
String word = words[i];
List<Integer> arr = map.get(word);
if (arr == null) {
arr = new ArrayList<Integer>();
map.put(word, arr);
}
arr.add(i);
}
int dis = words.length;
List<Integer> arr1 = map.get(word1);
List<Integer> arr2 = map.get(word2);
for (int a1 : arr1) {
for (int a2 : arr2) {
dis = Math.min(dis, Math.abs(a1 - a2));
}
}
return dis;
}
}
====
public class Solution {
public int shortestDistance(String[] words, String word1, String word2) {
int p1 = -1;
int p2 = -1;
int res = words.length;
for (int i = 0; i < words.length; i++) {
String word = words[i];
if (word.equals(word1)) {
p1 = i;
}
if (word.equals(word2)) {
p2 = i;
}
if (p1 != -1 && p2 != -1) {
res = Math.min(res, Math.abs(p1 - p2));
}
}
return res;
}
}
没有评论:
发表评论