LeetCode599 Minimum Index Sum of Two Lists

文章目录
  1. 1. 题目
  2. 2. 思路
  3. 3. 代码

题目

LeetCode599 Minimum Index Sum of Two Lists

思路

找出交集中下标和最小值.

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
vector<string> findRestaurant(vector<string>& list1, vector<string>& list2) {
vector<string> ans;
int n = list1.size(), m = list2.size();
unordered_map<string, int> hs;
for (int i = 0; i < n; ++i) hs[list1[i]] = i;
int minSum = INT_MAX;
for (int i = 0; i < m; ++i) {
if (hs.count(list2[i])) {
int j = hs[list2[i]];
if (i + j < minSum) {
minSum = i + j;
ans.clear();
ans.push_back(list2[i]);
} else if (i + j == minSum) {
ans.push_back(list2[i]);
}
}
}
return ans;
}
};
分享到 评论