File tree Expand file tree Collapse file tree 2 files changed +17
-5
lines changed
Expand file tree Collapse file tree 2 files changed +17
-5
lines changed Original file line number Diff line number Diff line change @@ -41,9 +41,21 @@ https://leetcode-cn.com/problems/two-sum
4141
4242## 思路
4343
44- 最容易想到的就是暴力枚举,我们可以利用两层 for 循环来遍历每个元素,并查找满足条件的目标元素。不过这样时间复杂度为 O(N^2),空间复杂度为 O(1),时间复杂度较高,我们要想办法进行优化。
44+ 最容易想到的就是暴力枚举,我们可以利用两层 for 循环来遍历每个元素,并查找满足条件的目标元素。
4545
46- 这里我们可以增加一个 Map 记录已经遍历过的数字及其对应的索引值。这样当遍历一个新数字的时候就去 Map 里查询 ** target 与该数的差值是否已经在前面的数字中出现过** 。如果出现过,就找到了答案,就不必再往下继续执行了。
46+ 伪代码:
47+
48+ ``` java
49+ for (int i = 0 ; i < n; i++ ) {
50+ for (int j = 0 ; j < i;j ++ ){
51+ if (nums[i] + nums[j] == target) return [j, i]
52+ }
53+ }
54+ ```
55+
56+ 不过这样时间复杂度为 O(N^2),空间复杂度为 O(1),时间复杂度较高,我们要想办法进行优化。
57+
58+ 这里我们可以增加一个 Map 记录已经遍历过的数字及其对应的索引值。这样当遍历一个新数字的时候就去 Map 里查询 ** target 与该数的差值 diff 是否已经在前面的数字中出现过** 。如果出现过,说明 diff + 当前数 = target,我们就找到了一组答案。
4759
4860## 关键点
4961
@@ -112,7 +124,7 @@ public:
112124- 时间复杂度:$O(N)$
113125- 空间复杂度:$O(N)$
114126
115- 更多题解可以访问我的 LeetCode 题解仓库:https://github.com/azl397985856/leetcode 。 目前已经 37K star 啦。
127+ 更多题解可以访问我的 LeetCode 题解仓库:https://github.com/azl397985856/leetcode 。 目前已经 40K star 啦。
116128
117129关注公众号力扣加加,努力用清晰直白的语言还原解题思路,并且有大量图解,手把手教你识别套路,高效刷题。
118130
Original file line number Diff line number Diff line change @@ -77,12 +77,12 @@ https://leetcode-cn.com/problems/valid-parentheses/description
7777
7878(图片来自: https://github.com/MisterBooo/LeetCodeAnimation )
7979
80- > 值得注意的是,如果题目要求只有一种括号,那么我们其实可以使用更简洁,更省内存的方式 - 计数器来进行求解,而不必要使用栈。
80+ 值得注意的是,如果题目要求只有一种括号,那么我们其实可以使用更简洁,更省内存的方式 - 计数器来进行求解,而不必要使用栈。 而之所以多种括号不可以使用计数器在 $O(1)$ 空间做到是因为类似这种用例会无法处理 "( [ ) ] " 。
8181
8282### 关键点解析
8383
84841 . 栈的基本特点和操作
85- 2 . 如果你用的是 JS 没有现成的栈,可以用数组来模拟。
85+ 2 . 可以用数组来模拟栈
8686
8787比如 入: push 出:pop 就是栈。 入: push 出 shift 就是队列。 但是这种算法实现的队列在头部删除元素的时候时间复杂度比较高,具体大家可以参考一下[ 双端队列 deque] ( https://zh.wikipedia.org/wiki/%E5%8F%8C%E7%AB%AF%E9%98%9F%E5%88%97 ) 。
8888
You can’t perform that action at this time.
0 commit comments