1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| class Solution { Map<String, List<Integer>> map = new HashMap<>(); public int findClosest(String[] words, String word1, String word2) { for (int i = 0; i < words.length; i++) { if (map.containsKey(words[i])) { List<Integer> list = map.get(words[i]); list.add(i); map.put(words[i], list); }else { List<Integer> tmp = new ArrayList<>(); tmp.add(i); map.put(words[i], tmp); } }
List<Integer> list1 = map.get(word1); List<Integer> list2 = map.get(word2);
int result = Integer.MAX_VALUE; for (int i = 0; i < list1.size(); i++) { int frist = list1.get(i); for (int j = 0; j < list2.size(); j++) { int sec = list2.get(j); int ans = Math.abs(frist - sec); result = Math.min(result, ans); } } return result; } }
|