1
1
<p align =" center " >
2
- <a href =" https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ " ><img src =" https://img.shields.io/badge/知识星球-代码随想录-blue " alt =" " ></a >
3
- <a href =" https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw " ><img src =" https://img.shields.io/badge/刷题-微信群-green " alt =" " ></a >
4
- <a href =" https://img-blog.csdnimg.cn/20201210231711160.png " ><img src =" https://img.shields.io/badge/公众号-代码随想录-brightgreen " alt =" " ></a >
5
- <a href =" https://space.bilibili.com/525438321 " ><img src =" https://img.shields.io/badge/B站-代码随想录-orange " alt =" " ></a >
6
- </p >
7
- <p align =" center " ><strong >欢迎大家参与本项目,贡献其他语言版本的代码,拥抱开源,让更多学习算法的小伙伴们收益!</strong ></p >
2
+ <a href =" https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ " target =" _blank " >
3
+ <img src =" https://code-thinking-1253855093.file.myqcloud.com/pics/20210924105952.png " width =" 1000 " />
4
+ </a >
5
+ <p align =" center " ><strong ><a href =" https://mp.weixin.qq.com/s/tqCxrMEU-ajQumL1i8im9A " >参与本项目</a >,贡献其他语言版本的代码,拥抱开源,让更多学习算法的小伙伴们收益!</strong ></p >
8
6
9
7
10
8
## 1. 两数之和
11
9
12
- https://leetcode-cn.com/problems/two-sum/
10
+ [ 力扣题目链接 ] ( https://leetcode-cn.com/problems/two-sum/ )
13
11
14
12
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
15
13
@@ -29,10 +27,10 @@ https://leetcode-cn.com/problems/two-sum/
29
27
很明显暴力的解法是两层for循环查找,时间复杂度是O(n^2)。
30
28
31
29
建议大家做这道题目之前,先做一下这两道
32
- * [ 242. 有效的字母异位词] ( https://mp.weixin.qq. com/s/vM6OszkM6L1Mx2Ralm9Dig )
33
- * [ 349. 两个数组的交集] ( https://mp.weixin.qq. com/s/N9iqAchXreSVW7zXUS4BVA )
30
+ * [ 242. 有效的字母异位词] ( https://www.programmercarl. com/0242.有效的字母异位词.html )
31
+ * [ 349. 两个数组的交集] ( https://www.programmercarl. com/0349.两个数组的交集.html )
34
32
35
- [ 242. 有效的字母异位词] ( https://mp.weixin.qq. com/s/vM6OszkM6L1Mx2Ralm9Dig ) 这道题目是用数组作为哈希表来解决哈希问题,[ 349. 两个数组的交集] ( https://mp.weixin.qq. com/s/N9iqAchXreSVW7zXUS4BVA ) 这道题目是通过set作为哈希表来解决哈希问题。
33
+ [ 242. 有效的字母异位词] ( https://www.programmercarl. com/0242.有效的字母异位词.html ) 这道题目是用数组作为哈希表来解决哈希问题,[ 349. 两个数组的交集] ( https://www.programmercarl. com/0349.两个数组的交集.html ) 这道题目是通过set作为哈希表来解决哈希问题。
36
34
37
35
本题呢,则要使用map,那么来看一下使用数组和set来做哈希法的局限。
38
36
@@ -51,17 +49,18 @@ C++中map,有三种类型:
51
49
52
50
std::unordered_map 底层实现为哈希表,std::map 和std::multimap 的底层实现是红黑树。
53
51
54
- 同理,std::map 和std::multimap 的key也是有序的(这个问题也经常作为面试题,考察对语言容器底层的理解)。 更多哈希表的理论知识请看[ 关于哈希表,你该了解这些!] ( https://mp.weixin.qq. com/s/g8N6WmoQmsCUw3_BaWxHZA ) 。
52
+ 同理,std::map 和std::multimap 的key也是有序的(这个问题也经常作为面试题,考察对语言容器底层的理解)。 更多哈希表的理论知识请看[ 关于哈希表,你该了解这些!] ( https://www.programmercarl. com/哈希表理论基础.html ) 。
55
53
56
54
** 这道题目中并不需要key有序,选择std::unordered_map 效率更高!**
57
55
58
56
解题思路动画如下:
59
57
60
- <video src =' https://code-thinking.cdn.bcebos.com/gifs/1.%E4%B8%A4%E6%95%B0%E4%B9%8B%E5%92%8C.mp4 ' controls =' controls ' width =' 640 ' height =' 320 ' autoplay =' autoplay ' > Your browser does not support the video tag.</video ></div >
58
+ ![ ] ( https://code-thinking.cdn.bcebos.com/gifs/1.两数之和.gif )
59
+
61
60
62
61
C++代码:
63
62
64
- ``` C++
63
+ ``` CPP
65
64
class Solution {
66
65
public:
67
66
vector<int > twoSum(vector<int >& nums, int target) {
@@ -106,16 +105,17 @@ public int[] twoSum(int[] nums, int target) {
106
105
107
106
Python:
108
107
109
- ``` python3
108
+ ``` python
110
109
class Solution :
111
110
def twoSum (self , nums : List[int ], target : int ) -> List[int ]:
112
- hashmap= {}
113
- for ind,num in enumerate (nums):
114
- hashmap[num] = ind
115
- for i,num in enumerate (nums):
116
- j = hashmap.get(target - num)
117
- if j is not None and i!= j:
118
- return [i,j]
111
+ records = dict ()
112
+
113
+ # 用枚举更方便,就不需要通过索引再去取当前位置的值
114
+ for idx, val in enumerate (nums):
115
+ if target - val not in records:
116
+ records[val] = idx
117
+ else :
118
+ return [records[target - val], idx] # 如果存在就返回字典记录索引和当前索引
119
119
```
120
120
121
121
@@ -134,6 +134,21 @@ func twoSum(nums []int, target int) []int {
134
134
}
135
135
```
136
136
137
+ ``` go
138
+ // 使用map方式解题,降低时间复杂度
139
+ func twoSum (nums []int , target int ) []int {
140
+ m := make (map [int ]int )
141
+ for index , val := range nums {
142
+ if preIndex , ok := m[target-val]; ok {
143
+ return []int {preIndex, index}
144
+ } else {
145
+ m[val] = index
146
+ }
147
+ }
148
+ return []int {}
149
+ }
150
+ ```
151
+
137
152
Rust
138
153
139
154
``` rust
@@ -156,11 +171,81 @@ impl Solution {
156
171
}
157
172
```
158
173
174
+ Javascript
159
175
176
+ ``` javascript
177
+ var twoSum = function (nums , target ) {
178
+ let hash = {};
179
+ for (let i = 0 ; i < nums .length ; i++ ) {
180
+ if (hash[target - nums[i]] !== undefined ) {
181
+ return [i, hash[target - nums[i]]];
182
+ }
183
+ hash[nums[i]] = i;
184
+ }
185
+ return [];
186
+ };
187
+ ```
160
188
189
+ php
190
+
191
+ ``` php
192
+ function twoSum(array $nums, int $target): array
193
+ {
194
+ for ($i = 0; $i < count($nums);$i++) {
195
+ // 计算剩下的数
196
+ $residue = $target - $nums[$i];
197
+ // 匹配的index,有则返回index, 无则返回false
198
+ $match_index = array_search($residue, $nums);
199
+ if ($match_index !== false && $match_index != $i) {
200
+ return array($i, $match_index);
201
+ }
202
+ }
203
+ return [];
204
+ }
205
+ ```
206
+
207
+ Swift:
208
+ ``` swift
209
+ func twoSum (_ nums : [Int ], _ target : Int ) -> [Int ] {
210
+ var res = [Int ]()
211
+ var dict = [Int : Int ]()
212
+ for i in 0 ..< nums.count {
213
+ let other = target - nums[i]
214
+ if dict.keys .contains (other) {
215
+ res.append (i)
216
+ res.append (dict[other]! )
217
+ return res
218
+ }
219
+ dict[nums[i]] = i
220
+ }
221
+ return res
222
+ }
223
+ ```
224
+
225
+ PHP:
226
+ ``` php
227
+ class Solution {
228
+ /**
229
+ * @param Integer[] $nums
230
+ * @param Integer $target
231
+ * @return Integer[]
232
+ */
233
+ function twoSum($nums, $target) {
234
+ if (count($nums) == 0) {
235
+ return [];
236
+ }
237
+ $table = [];
238
+ for ($i = 0; $i < count($nums); $i++) {
239
+ $temp = $target - $nums[$i];
240
+ if (isset($table[$temp])) {
241
+ return [$table[$temp], $i];
242
+ }
243
+ $table[$nums[$i]] = $i;
244
+ }
245
+ return [];
246
+ }
247
+ }
248
+ ```
161
249
162
250
-----------------------
163
- * 作者微信:[ 程序员Carl] ( https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw )
164
- * B站视频:[ 代码随想录] ( https://space.bilibili.com/525438321 )
165
- * 知识星球:[ 代码随想录] ( https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ )
166
- <div align="center"><img src=../pics/公众号.png width=450 alt=> </img ></div >
251
+ <div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img ></div >
0 commit comments