# leetcode-599-Minimum Index Sum of Two Lists

### 题目描述：

Suppose Andy and Doris want to choose a restaurant for dinner, and they both have a list of favorite restaurants represented by strings.

You need to help them find out their common interest with the least list index sum. If there is a choice tie between answers, output all of them with no order requirement. You could assume there always exists an answer.

Example 1:

```Input:
["Shogun", "Tapioca Express", "Burger King", "KFC"]
["Piatti", "The Grill at Torrey Pines", "Hungry Hunter Steakhouse", "Shogun"]
Output: ["Shogun"]
Explanation: The only restaurant they both like is "Shogun".```

Example 2:

```Input:
["Shogun", "Tapioca Express", "Burger King", "KFC"]
["KFC", "Shogun", "Burger King"]
Output: ["Shogun"]
Explanation: The restaurant they both like and have the least index sum is "Shogun" with index sum 1 (0+1).```

Note:

1. The length of both lists will be in the range of [1, 1000].
2. The length of strings in both lists will be in the range of [1, 30].
3. The index is starting from 0 to the list length minus 1.
4. No duplicates in both lists.

### 要完成的函数：

vector<string> findRestaurant(vector<string>& list1, vector<string>& list2)

### 说明：

1、给定两个vector，里面分别存储两个人的喜好餐厅名字，最开始是最喜欢的，接下来其次……这样子排列下去。

2、首先，如果想要花费时间够少，我们可以增加空间复杂度，使用map来存储给定vector中的餐厅名字和餐厅的喜好顺序。

```    vector<string> findRestaurant(vector<string>& list1, vector<string>& list2)
{
unordered_map<string,int>m1;//使用unordered_map速度更快
int min1=INT_MAX;
int j,t;
vector<string>res;
for(int i=0;i<list1.size();i++)//存储餐厅名称和喜好顺序
m1[list1[i]]=i;
for(int i=0;i<list2.size();i++)
{
if(m1.count(list2[i])==0)//如果没有出现过，那么不是共同餐厅
continue;
else
min1=min(min1,m1[list2[i]]+i);//存储最小的喜好顺序的和
}
for(int i=0;i<list2.size();i++)
{
if(m1.count(list2[i])==0)//如果没有出现过，那么不是共同餐厅
continue;
else
{
if((m1[list2[i]]+i)==min1)//如果等于最小值，那么存储
res.push_back(list2[i]);
}
}
return res;
}```

3、改进：

```    vector<string> findRestaurant(vector<string>& list1, vector<string>& list2)
{
vector<string>res;
unordered_map<string,int>m1;
int min1=INT_MAX;
for(int i = 0; i < list1.size(); i++)
m1[list1[i]] = i;
for(int i = 0; i < list2.size(); i++)
{
if(m1.count(list2[i]) != 0)
{
if(m1[list2[i]] + i < min1)
{
min1=m1[list2[i]] + i;
res.clear();
res.push_back(list2[i]);
}
else if(m1[list2[i]] + i == min1)
res.push_back(list2[i]);
}

}
return res;
}```

205 篇文章43 人订阅

0 条评论

## 相关文章

我们经常提到函数式编程就是F[T]。这个F可以被视为一种运算模式。我们是在F运算模式的壳子内对T进行计算。理论上来讲，函数式程序的运行状态也应该是在这个运算...

2998

3214

1779

### JUC包下的CountDownLatch,CyclicBarrier,Semaphore

①.从CountDownLatch的设计来看,可以做汇总的操作,例如计算员工工资,这边启动多个线程同时计算等所有线程执行完毕之后,计算需要发放的总额 final...

2298

3105

4158

1042

3588

34111

2498