Skip to content

Commit 5bdd117

Browse files
committed
Update two-sum with cpp
1 parent ce4ab0c commit 5bdd117

File tree

2 files changed

+29
-5
lines changed

2 files changed

+29
-5
lines changed

basic/binary-tree/18.vertical-order-traversal-of-a-binary-tree.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -209,3 +209,5 @@ var verticalTraversal = function (root) {
209209
}
210210
};
211211
```
212+
213+
更多题解可以访问:[https://github.com/suukii/91-days-algorithm](https://github.com/suukii/91-days-algorithm)

basic/hashmap/19.two-sum.md

Lines changed: 27 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,15 +7,15 @@ https://leetcode-cn.com/problems/two-sum
77
- [方法 1:哈希表](#方法-1哈希表)
88
- [思路](#思路)
99
- [复杂度分析](#复杂度分析)
10-
- [代码](#代码)
10+
- [代码(JavaScript/Python/C++)](#代码javascriptpythonc)
1111
- [方法 2:排序+双指针](#方法-2排序双指针)
1212
- [思路](#思路-1)
1313
- [复杂度分析](#复杂度分析-1)
14-
- [代码](#代码-1)
14+
- [代码](#代码)
1515
- [方法 3:暴力法](#方法-3暴力法)
1616
- [思路](#思路-2)
1717
- [复杂度分析](#复杂度分析-2)
18-
- [代码](#代码-2)
18+
- [代码](#代码-1)
1919

2020
## 题目描述
2121

@@ -51,7 +51,7 @@ https://leetcode-cn.com/problems/two-sum
5151
- 时间复杂度:$O(N)$,N 为数组长度,最坏的情况下数组中的每个元素都被访问一次,访问数组元素的时间是 $O(1)$,哈希表插入和查询元素的时间也是 $O(1)$。
5252
- 空间复杂度:$O(N)$,N 为数组长度,用来存元素和下标的哈希表所需的空间。
5353

54-
### 代码
54+
### 代码(JavaScript/Python/C++)
5555

5656
JavaScript Code
5757

@@ -93,6 +93,26 @@ class Solution(object):
9393
hashmap[n] = i
9494
```
9595

96+
C++ Code
97+
98+
```cpp
99+
class Solution {
100+
public:
101+
vector<int> twoSum(vector<int>& nums, int target) {
102+
map<int, int> seen;
103+
for (int i = 0; i < nums.size(); i++) {
104+
int sub = target - nums[i];
105+
auto it = seen.find(sub);
106+
if (it != seen.end()) {
107+
return {it->second, i};
108+
}
109+
seen[nums[i]] = i;
110+
}
111+
return {};
112+
}
113+
};
114+
```
115+
96116
## 方法 2:排序+双指针
97117
98118
### 思路
@@ -103,7 +123,7 @@ class Solution(object):
103123
### 复杂度分析
104124
105125
- 时间复杂度:$O(NlogN)$,N 为数组长度。
106-
- 空间复杂度:$O(1)$。(不是很确定,是 $O(1)$ 还是 $O(N)$
126+
- 空间复杂度:$O(N)$
107127
108128
### 代码
109129
@@ -170,3 +190,5 @@ var twoSum = function (nums, target) {
170190
}
171191
};
172192
```
193+
194+
更多题解可以访问:[https://github.com/suukii/91-days-algorithm](https://github.com/suukii/91-days-algorithm)

0 commit comments

Comments
 (0)