-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path01.twoSum.cpp
More file actions
43 lines (40 loc) · 980 Bytes
/
Copy path01.twoSum.cpp
File metadata and controls
43 lines (40 loc) · 980 Bytes
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
//
// Created by cwb on 2022/6/9.
//
#include "leetCodeCommonDefine.h"
/*
* difficulty:easy
* 解法一:暴力解法(o(n^2))
* 解法二:哈希表(o(n))
*/
class Solution
{
public:
std::vector<int> twoSum(std::vector<int>& nums, int target)
{
std::map<int, int> flag;
for (int i = 0; i < nums.size(); ++i)
{
auto num = nums[i];
if (flag.find(target - num) != flag.end())
{
return { flag[target - num], i };
}
flag[num] = i;
}
return { 0, 0 };
}
};
void twoSumTest()
{
std::string line;
while (getline(std::cin, line))
{
std::vector<int> nums = stringToIntegerVector(line);
getline(std::cin, line);
int target = stringToInteger(line);
std::vector<int> ret = Solution().twoSum(nums, target);
std::string out = integerVectorToString(ret);
std::cout << out << std::endl;
}
}