https://leetcode.com/problems/minimum-index-sum-of-two-lists/description/
Solution 1. Hash table
vector<string> findRestaurant(vector<string>& list1, vector<string>& list2) {
unordered_map<string,int> m;
vector<string> res;
int least = INT_MAX, s;
for(int i=0;i<list1.size();i++) {
m[list1[i]] = i;
}
for(int i=0;i<list2.size();i++) {
if(m.count(list2[i])) {
s = i+m[list2[i]];
if( s == least) {
res.push_back(list2[i]);
}
else if(s < least){
res.clear();
res.push_back(list2[i]);
least = s;
}
}
}
return res;
}
No comments:
Post a Comment