599. 两个列表的最小索引总和
假设Andy和Doris想在晚餐时选择一家餐厅,并且他们都有一个表示最喜爱餐厅的列表,每个餐厅的名字用字符串表示。
你需要帮助他们用最少的索引和找出他们共同喜爱的餐厅。 如果答案不止一个,则输出所有答案并且不考虑顺序。 你可以假设总是存在一个答案。
示例 1:
输入:["Shogun", "Tapioca Express", "Burger King", "KFC"]["Piatti", "The Grill at Torrey Pines", "Hungry Hunter Steakhouse", "Shogun"]输出: ["Shogun"]解释: 他们唯一共同喜爱的餐厅是“Shogun”。示例 2:
输入:["Shogun", "Tapioca Express", "Burger King", "KFC"]["KFC", "Shogun", "Burger King"]输出: ["Shogun"]解释: 他们共同喜爱且具有最小索引和的餐厅是“Shogun”,它有最小的索引和1(0+1)。提示:
两个列表的长度范围都在 [1, 1000]内。两个列表中的字符串的长度将在[1,30]的范围内。下标从0开始,到列表的长度减1。两个列表都没有重复的元素。
第一版,自己写的,速度快,内存较大
vector<string>findRestaurant(vector<string>&list1, vector<string>&list2) {
unordered_map<string, pair<int, int>>res;//餐厅名 索引号相加 ,出现次数
intminIndex=INT_MAX;
multimap<int,string>result;
for (unsignedi=0; i<list1.size(); ++i) {
res[list1[i]] = { i,1 };
}
for (unsignedi=0; i<list2.size(); ++i) {
res[list2[i]].first+=i;
res[list2[i]].second+=1;
}
for (auto&a : res) {
if (a.second.second==2) {
minIndex=a.second.first<minIndex?a.second.first : minIndex;
result.insert({ a.second.first, a.first});
}
}
multimap<int, string>::iteratorbeg, end;
beg =result.equal_range(minIndex).first;
end=result.equal_range(minIndex).second;
vector<string>r;
while (beg!=end) {
r.push_back(beg->second);
beg++;
}
returnr;
}
第二版,换了一个写法,反而更差了...
执行用时 :188 ms, 在所有 cpp 提交中击败了40.00%的用户
内存消耗 :32.3 MB, 在所有 cpp 提交中击败了14.21%的用户
vector<string>findRestaurant(vector<string>&list1, vector<string>&list2) {
unordered_map<string, pair<int, int>>res;//餐厅名 索引号相加 ,出现次数
intminIndex;
vector<string>result;
for (unsignedi=0; i<list1.size(); ++i) {
res[list1[i]] = { i,1 };
}
for (unsignedi=0; i<list2.size(); ++i) {
res[list2[i]].first+=i;
res[list2[i]].second+=1;
}
for (auto&a : res) {
if (a.second.second==2) {
if (result.empty()) {//第一次为空直接进
minIndex=a.second.first;
result.push_back(a.first);
}
else//不为空,与上一次最小值进行比较
{
if (a.second.first<minIndex) //当前最小值是最小的,进行更替
{
result.clear();//清空结果
minIndex=a.second.first;
result.push_back(a.first);
}
elseif (a.second.first==minIndex)//和当前一样大,就直接进去
{
result.push_back(a.first);
}
}
}
}
returnresult;
}
第三版,再换一个写法。。。还是第一版最快
执行用时 :180 ms, 在所有 cpp 提交中击败了44.26%的用户
内存消耗 :32.2 MB, 在所有 cpp 提交中击败了14.74%的用户
vector<string>findRestaurant(vector<string>&list1, vector<string>&list2) {
unordered_map<string, pair<int, int>>res;//餐厅名 索引号相加 ,出现次数
intminIndex;
vector<string>result;
for (unsignedi=0; i<list1.size(); ++i) {
res[list1[i]] = { i,1 };
}
for (unsignedi=0; i<list2.size(); ++i) {
res[list2[i]].first+=i;
res[list2[i]].second+=1;
if (res[list2[i]].second==2)
{
if (result.empty()) {//第一次为空直接进
minIndex=res[list2[i]].first;
result.push_back(list2[i]);
}
else//不为空,与上一次最小值进行比较
{
if (res[list2[i]].first<minIndex) //当前最小值是最小的,进行更替
{
result.clear();//清空结果
minIndex=res[list2[i]].first;
result.push_back(list2[i]);
}
elseif (res[list2[i]].first==minIndex)//和当前一样大,就直接进去
{
result.push_back(list2[i]);
}
}
}
}
returnresult;
}