Title Description
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.
Example 1:
Input: ["Shogun", "Tapioca Express", "Burger King", "KFC"] ["Piatti", "The Grill at Torrey Pines", "Hungry Hunter Steakhouse", "Shogun"] Output: ["Shogun"] Explanation: The only restaurant they both like is "Shogun".
Example 2:
Input: ["Shogun", "Tapioca Express", "Burger King", "KFC"] ["KFC", "Shogun", "Burger King"] Output: ["Shogun"] Explanation: The restaurant they both like and have the least index sum is "Shogun" with index sum 1 (0+1).
Answers
1 class Solution { 2 public: 3 vector<string> findRestaurant(vector<string>& list1, vector<string>& list2) { 4 5 vector<string> res; 6 unordered_map<string, int> map; 7 for(size_t i = 0 ; i< list1.size(); i++) 8 map[list1[i]] = i ; // list1 = key ; i = value ; 9 10 size_t min =INT_MAX; . 11 12 is for (size_t I = 0 ; I <list2.size (); I ++ ) { 13 is Auto ITER = map.find (List2 [I]); 14 IF (! = ITER map.end ()) { 15 IF (iter-> sECOND + I < min) { 16 min = Map [List2 [I]] + I; . 17 res.assign ( . 1 , List2 [I]); // directly to assign a value to a first , clear and does not need to be reassigned 18 is . 19 } the else IF (iter-> SECOND == + I min) { 20 is res.push_back(list2[i]); 21 } 22 23 } 24 } 25 return res; 26 } 27 };
Analysis Remarks
1. for loop, int size_t be replaced accelerated.
2. vector.assign (1, value) + assignment to clear or two steps.
3. iter -> first and iter -> second faster.