599. 两个列表的最小索引总和
首先通过哈希存储其中一个列表下标,遍历另一个列表每次比对答案下标之和,如果相等直接加到答案里面,如果更小那么清空之前的答案,同时更新最小下标和
class Solution {
public:
vector<string> findRestaurant(vector<string>& list1, vector<string>& list2) {
map<string, int> mp;
for (int i = 0; i < list1.size(); i ++ )
mp[list1[i]] = i;
vector<string> ans;
int minn = INT_MAX;
for (int j = 0; j < list2.size(); j ++ ) {
string s = list2[j];
if (mp.count(s)) {
if (mp[s] + j < minn) {
ans.clear();
ans.push_back(s);
minn = mp[s] + j;
}
else if (mp[s] + j == minn) {
ans.push_back(s);
}
}
}
return ans;
}
};