LeetCode知识点总结 - 599

LeetCode 599. Minimum Index Sum of Two Lists

考点 难度
Array Easy
题目

Suppose Andy and Doris want to choose a restaurant for dinner, and they both have a list of favorite restaurants represented by strings.

You need to help them find out their common interest with the least list index sum. If there is a choice tie between answers, output all of them with no order requirement. You could assume there always exists an answer.

思路

用HashMap储存list1里面的所有字符串和他们的位置。对于list2里面的字符串,判断是否在map里面并且计算在两个list里面的位置和。

答案
public String[] findRestaurant(String[] list1, String[] list2) {
        int sum_min = Integer.MAX_VALUE;
        int sum_temp = 0;
        List<String> str = new ArrayList<>();
        HashMap<String, Integer> map = new HashMap<String, Integer>();
        
        for(int i = 0; i < list1.length; i++){
            map.put(list1[i],  i);
        }
        
        for(int j = 0; j < list2.length && j<=sum_min; j++){
            if(map.containsKey(list2[j])){
                sum_temp = j + map.get(list2[j]);
                if (sum_temp < sum_min){
                    str.clear();
                    str.add(list2[j]);
                    sum_min = sum_temp;
                }
                else if(sum_temp == sum_min){
                    str.add(list2[j]);
                }
            }
        }
        return str.toArray(new String[str.size()]);
    }

猜你喜欢

转载自blog.csdn.net/m0_59773145/article/details/120041517