题意:找出两个人都喜欢的餐厅,返回序号之和最小的。
solution:hash记录餐馆名对应的序号之和。遍历第一个数组时,记录每一个餐厅的序号,遍历第二个数组时,仅处理在1中出现过的餐厅。
class Solution {
public:
vector<string> findRestaurant(vector<string>& list1, vector<string>& list2) {
// 对于所有count==2的,记录最小index sum如果有更小则 清空+插入 如果相等 则仅插入
// 1. hash
/*unordered_map<string, vector<int>> hash; // name-(count,index sum)
int min_index = 2000;
vector<string> res;
for ( int i = 0; i < list1.size(); i++ ) {
hash[list1[i]].push_back(1);
hash[list1[i]].push_back(i);
}
for ( int i = 0; i < list2.size(); i++ ) {
if ( hash.find(list2[i]) != hash.end() ) {
hash[list2[i]][0]++;
hash[list2[i]][1]+=i;
}
}
for ( auto n : hash ) {
if ( n.second[0] == 2 ) {
if ( n.second[1] < min_index ) {
res.clear();
res.push_back(n.first);
min_index = n.second[1];
}
else if ( n.second[1] == min_index )
res.push_back(n.first);
}
}*/
// 1.5 clever hash
unordered_map<string, int> hash; // name-index sum
vector<string> res;
int min_sum = 2000;
for ( int i = 0; i < list1.size(); i++ ) {
hash[list1[i]] = i;
}
for ( int i = 0; i < list2.size(); i++ ) {
if ( hash.find(list2[i]) != hash.end() ) {
if ( hash[list2[i]]+i <= min_sum ) {
if ( hash[list2[i]]+i < min_sum ) {
min_sum = hash[list2[i]]+i;
res.clear();
}
res.push_back(list2[i]);
}
}
}
return res;
}
};
submission: