599.两个列表的最小索引总和

题目

599.两个列表的最小索引总和

题目大意

假设 Andy 和 Doris 想在晚餐时选择一家餐厅,并且他们都有一个表示最喜爱餐厅的列表,每个餐厅的名字用字符串表示。

你需要帮助他们用最少的索引和找出他们共同喜爱的餐厅。 如果答案不止一个,则输出所有答案并且不考虑顺序。 你可以假设答案总是存在。

样例

image-20220314171813399

数据规模

image-20220314171819608

思路

使用哈希表unordered_map,首先遍历list1中的每一个字符串,在哈希表中进行标记。

定义一个最小索引和minn以及答案数组vector ans

遍历list2中的每一个字符串,并且判断mp[list2[i]]是否存在,并且计算索引和,如果可以更新minn则需要清空答案数组ans,然后加入当前的字符串;如果恰好等于最小索引和,那么直接将该字符串加入数组即可。

代码

// short int long float double bool char string void
// array vector stack queue auto const operator
// class public private static friend extern 
// sizeof new delete return cout cin memset malloc
// relloc size length memset malloc relloc size length
// for while if else switch case continue break system
// endl reverse sort swap substr begin end iterator
// namespace include define NULL nullptr exit equals 
// index col row arr err left right ans res vec que sta
// state flag ch str max min default charray std
// maxn minn INT_MAX INT_MIN push_back insert
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=1e6+50;//注意修改大小
long long read(){long long x=0,f=1;char c=getchar();while(!isdigit(c)){if(c=='-') f=-1;c=getchar();}while(isdigit(c)){x=x*10+c-'0';c=getchar();}return x*f;}
ll qpow(ll x,ll q,ll Mod){ll ans=1;while(q){if(q&1)ans=ans*x%Mod;q>>=1;x=(x*x)%Mod;}return ans%Mod;}

class Solution {
public:
    vector<string> findRestaurant(vector<string>& list1, vector<string>& list2) {
		unordered_map<string,int>mp;
		for(int i=0;i<list1.size();i++){
			mp[list1[i]]=i+1;
		}
		vector<string>ans;
		int minn=0x3f3f3f3f;
		for(int i=0;i<list2.size();i++){
			if(mp[list2[i]]&&minn>i+mp[list2[i]]-1){
				ans.clear();
				ans.push_back(list2[i]);
				minn=i+mp[list2[i]]-1;
			}
			else if(mp[list2[i]]&&minn==i+mp[list2[i]]-1){
				ans.push_back(list2[i]);
			}
		}
		return ans;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Phoenix_ZengHao

创作不易,能否打赏一瓶饮料?

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值