Minimum Index Sum of Two Lists
给两个list, 找到两个list的共同元素, 并且这里两个元素的index之和最小, 这里答案可以是很多个. 先找到这个最小值, 放到map里, 然后再找一次所有答案.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
class Solution { public String[] findRestaurant(String[] list1, String[] list2) { Map<String, Integer> m1 = new HashMap<>(); List<String> res = new ArrayList<>(); for(int i = 0 ; i < list1.length; i++) { m1.put(list1[i], i); } int min = Integer.MAX_VALUE; for(int i = 0 ; i < list2.length; i++) { if(m1.containsKey(list2[i])) { // find min min = Math.min(min, i + m1.get(list2[i])); m1.put(list2[i], i + m1.get(list2[i])); } } for(int i = 0 ; i < list2.length; i++) { if(m1.containsKey(list2[i]) && m1.get(list2[i]) == min) { // two lists share same element and it equals to min res.add(list2[i]); } } return res.toArray(new String[res.size()]); } } |