LeetCode algorithm_C++ - Minimum index sum of two lists

Suppose Andy and Doris want to choose a restaurant for dinner, and they both have a list of favorite restaurants, each named as a string.

You need to help them with minimal indexing and find their mutual favorite restaurants. If there is more than one answer, all answers are output without regard to order. You can assume the answer is always there.

Example 1:
Input: list1 = ["Shogun", "Tapioca Express", "Burger King", "KFC"], list2 = ["Piatti", "The Grill at Torrey Pines", "Hungry Hunter Steakhouse", "Shogun "]
Output: ["Shogun"]
Explanation: The only restaurant they both like is "Shogun".

Example 2:
Input: list1 = ["Shogun", "Tapioca Express", "Burger King", "KFC"], list2 = ["KFC", "Shogun", "Burger King"] Output: ["Shogun"
]
Explanation: The restaurant they both like together and has the smallest index sum is "Shogun", which has the smallest index sum 1 (0+1).

vector<string> findRestaurant(vector<string>& list1, vector<string>& list2) {
    
    
    unordered_map<string, int> us{
    
    };
    vector<string> res{
    
    };
    int minSum = INT32_MAX;
    int n1 = list1.size(), n2 = list2.size();
    for (int i = 0; i < n1; ++i) us.insert(make_pair(list1[i], i));
    for (int i = 0; i < n2; ++i) {
    
    
        auto it = us.find(list2[i]);
        if (it != us.end() && it->second + i < minSum) {
    
    
            res.clear();
            res.push_back(it->first);
            minSum = it->second + i;
        }
        else if (it != us.end() && it->second + i == minSum) res.push_back(it->first);
    }
    return res;
}

Guess you like

Origin blog.csdn.net/weixin_43945471/article/details/132723591