1. 程式人生 > >[leetcode]599. Minimum Index Sum of Two Lists

[leetcode]599. Minimum Index Sum of Two Lists

span i++ 結果 ont () max hashmap body col

哈希表應用比較典型

public String[] findRestaurant(String[] list1, String[] list2) {
        //哈希表存字符串和對應下標
        Map<String,Integer> map = new HashMap<>();
        List<String> res = new ArrayList<>();
        int min = Integer.MAX_VALUE;
        for (int i = 0; i < list1.length; i++) {
            map.put(list1[i],i);
        }
        
//不斷更新結果 for (int i = 0; i < list2.length; i++) { String str = list2[i]; if (map.containsKey(str)) { if (i+map.get(str)<min) { res.clear(); res.add(str); min = i+map.get(str); }
else if (i+map.get(str)==min) res.add(str); } } String[] s = new String[res.size()]; for (int i = 0; i < res.size(); i++) { s[i] = res.get(i); } return s; }

[leetcode]599. Minimum Index Sum of Two Lists