Skip to content

Commit f26d07d

Browse files
committed
added 136.
1 parent 38e99bc commit f26d07d

File tree

5 files changed

+51
-2
lines changed

5 files changed

+51
-2
lines changed

.gitmodules

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
[submodule "Catch"]
22
path = Catch
3-
url = https://github.com/philsquared/Catch
3+
url = https://github.com/catchorg/Catch2

136. Two Sum/README.md

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
# 思路(C++)
2+
3+
好久没登录 LeetCode, 今天一登录,发现 No. 1 的题目都没做。惭愧,而且还是个 Easy 的。
4+
于是决定顺手解决了。
5+
6+
另外,LeetCode 现在有 711 道题了,当初我按照从易到难排序也逐步有些过时了。早知道还不如按照编号顺序来解题呢。这样一天容易一天难的,还挺好玩。
7+
8+
----
9+
10+
这道题有点像找配对。找到 `a`,找到 `b`,让 `a + b = target`。那么肯定得遍历,遍历的过程中,记录什么,成了思考的关键。
11+
12+
既然是配对,那么 kv 结构是非常合适的,于是上了 Hash 表。让 key 就是要找的 `b`,让 value 记录 `a` 的 index,也就是结果需要的索引。
13+
14+
这样思路就很简单明了了。

136. Two Sum/TEST.cc

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
#define CATCH_CONFIG_MAIN
2+
#include "../Catch/single_include/catch.hpp"
3+
#include "solution.h"
4+
5+
TEST_CASE("Two Sum", "twoSum")
6+
{
7+
Solution s;
8+
9+
std::vector<int> v1{2, 7, 11, 15};
10+
REQUIRE( (s.twoSum(v1, 9) == std::vector<int>{0, 1}) );
11+
12+
std::vector<int> v2{0, 4, 3, 0};
13+
REQUIRE( (s.twoSum(v2, 0) == std::vector<int>{0, 3}) );
14+
15+
std::vector<int> v3{-3, 4, 3, 90};
16+
REQUIRE( (s.twoSum(v3, 0) == std::vector<int>{0, 2}) );
17+
}

136. Two Sum/solution.h

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
#include <vector>
2+
using std::vector;
3+
#include <unordered_map>
4+
using std::unordered_map;
5+
6+
class Solution {
7+
public:
8+
vector<int> twoSum(vector<int>& nums, int target) {
9+
std::unordered_map<int, int> record;
10+
for (int i = 0; i != nums.size(); ++i) {
11+
auto found = record.find(nums[i]);
12+
if (found != record.end())
13+
return {found->second, i};
14+
record.emplace(target - nums[i], i);
15+
}
16+
return {-1, -1};
17+
}
18+
};

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
LeetCode
22
========
33

4-
LeetCode solutions in C++ 11. (From Easy to Hard)
4+
LeetCode solutions in C++ 11 and Python.
55

66
|NO.|Title|Solution|Add Date|Difficulty|
77
|---|-----|--------|--------|----------|

0 commit comments

Comments
 (0)