-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathminimum_index_sum.cpp
77 lines (68 loc) · 1.93 KB
/
minimum_index_sum.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/*
* =====================================================================================
*
* Filename: minimum_index_sum.cpp
*
* Description: Minimum Index Sum of Two Lists.
*
* Version: 1.0
* Created: 02/25/19 08:15:06
* Revision: none
* Compiler: gcc
*
* Author: Zhu Xianfeng (), [email protected]
* Organization:
*
* =====================================================================================
*/
#include <stdio.h>
#include <string>
#include <vector>
#include <unordered_map>
class Solution
{
public:
std::vector<std::string> findRestaurant(const std::vector<std::string>& list1, const std::vector<std::string>& list2)
{
std::unordered_map<std::string, int> indexes;
std::vector<std::string> rests;
int least = list1.size() + list2.size();
for (size_t i = 0; i < list1.size(); i++)
{
indexes[list1[i]] = i;
}
for (size_t j = 0; j < list2.size(); j++)
{
auto iter = indexes.find(list2[j]);
if (iter == indexes.end())
{
continue;
}
int sum = iter->second + j;
if (sum > least)
{
continue;
}
else if (sum < least)
{
rests.clear();
}
// sum <= least
rests.push_back(list2[j]);
least = sum;
}
return rests;
}
};
int main(int argc, char* argv[])
{
std::vector<std::string> list1 = {"Shogun", "Tapioca Express", "Burger King", "KFC"};
std::vector<std::string> list2 = {"Piatti", "The Grill at Torrey Pines", "Hungry Hunter Steakhouse", "Shogun"};
auto rests = Solution().findRestaurant(list1, list2);
for (const auto& item: rests)
{
printf("%s ", item.c_str());
}
printf("%s\n", (rests.size() > 0) ? "" : "None");
return 0;
}