File tree Expand file tree Collapse file tree 2 files changed +68
-1
lines changed
docs/problems/data-structure Expand file tree Collapse file tree 2 files changed +68
-1
lines changed Original file line number Diff line number Diff line change
1
+ ---
2
+ title : 1. 两数之和
3
+ sidebarDepth : 0
4
+ autoGroup-3 : 哈希表
5
+ ---
6
+ ## 简介
7
+ - [ 题目链接] ( https://leetcode-cn.com/problems/two-sum/ )
8
+
9
+ ## 解题思路
10
+ 本题很容易通过两次遍历(暴力枚举)的思路来解决,但是时间复杂度并不是我们所期望的。
11
+
12
+ 思考一个数学问题:
13
+ $a+b = target$,假设 $target$ 是定量,$a$, $b$ 是变量,那么我们可以使用 $a = target - b$ 来表示。这样,我们就可以将两个变量变为了一个变量。而实际上两次遍历处理的就是所有 $a$ 和 $b$ 的可能,将两个变量变为一个变量可以消除掉一个遍历。这样时间复杂度就降低到 $O(n)$
14
+
15
+
16
+
17
+ ### 解法一 - 哈希表(二次遍历)
18
+ #### 思路
19
+ 1 . 提前用哈希表将所有可能的 $a$ 存储起来,这里考虑到可能存在重复元素,因此 value 使用的数组。
20
+ 2 . 第二次遍历来看 $target-a$ 是否存在
21
+
22
+
23
+
24
+ ``` javascript
25
+ var twoSum = function (nums , target ) {
26
+ let map = {};
27
+
28
+ for (let i = 0 ; i < nums .length ; i++ ) {
29
+ if (map[nums[i]]) map[nums[i]].push (i);
30
+ else map[nums[i]] = [i];
31
+ }
32
+
33
+ for (let i = 0 ; i < nums .length ; i++ ) {
34
+ if ((target - nums[i] === nums[i])){
35
+ if (map[nums[i]] && map[nums[i]].length > 1 ) return [map[nums[i]][0 ], map[nums[i]][1 ]];
36
+ else continue ;
37
+ }
38
+ if (map[target- nums[i]]) return [i, map[target- nums[i]][0 ]];
39
+ }
40
+
41
+ return null ;
42
+ };
43
+ ```
44
+ ** 复杂度分析:**
45
+ - 时间复杂度: $O(N)$
46
+ - 空间复杂度: $O(N)$
47
+
48
+
49
+ ** 实际上,上面的提前存储显得有点多余。我们可以在遍历的同时存储前面的值。因为对于答案 $(i,j)$ 来讲,$j$ 只会依赖于前面已经处理过的值**
50
+
51
+ ``` javascript
52
+ var twoSum = function (nums , target ) {
53
+ let map = {};
54
+
55
+ for (let i = 0 ; i < nums .length ; i++ ) {
56
+ let index = map[target- nums[i]];
57
+ if (index) {
58
+ return [index- 1 , i];
59
+ } else {
60
+ map[nums[i]] = i+ 1 ; // 目的处理下标为 0 的情况
61
+ }
62
+
63
+ }
64
+
65
+ return null ;
66
+ };
67
+ ```
Original file line number Diff line number Diff line change 2
2
title : 41. 缺失的第一个正数
3
3
sidebarDepth : 0
4
4
autoGroup-3 : 哈希表
5
+ autoPrev : " 1"
5
6
---
6
7
## 简介
7
8
- [ 题目链接] ( https://leetcode-cn.com/problems/first-missing-positive/ )
8
- - [ 本地代码链接] ( ./../code/JavaScript/41.js )
9
9
10
10
## 解题思路
11
11
### 解法一 - 哈希表
You can’t perform that action at this time.
0 commit comments