File tree Expand file tree Collapse file tree 2 files changed +31
-5
lines changed Expand file tree Collapse file tree 2 files changed +31
-5
lines changed Original file line number Diff line number Diff line change 37
37
38
38
两层for循环就可以确定 a 和b 的数值了,可以使用哈希法来确定 0-(a+b) 是否在 数组里出现过,其实这个思路是正确的,但是我们有一个非常棘手的问题,就是题目中说的不可以包含重复的三元组。
39
39
40
- 把符合条件的三元组放进vector中,然后在去去重 ,这样是非常费时的,很容易超时,也是这道题目通过率如此之低的根源所在。
40
+ 把符合条件的三元组放进vector中,然后再去重 ,这样是非常费时的,很容易超时,也是这道题目通过率如此之低的根源所在。
41
41
42
42
去重的过程不好处理,有很多小细节,如果在面试中很难想到位。
43
43
@@ -95,11 +95,11 @@ public:
95
95
96
96

97
97
98
- 拿这个nums数组来举例,首先将数组排序,然后有一层for循环,i从下表0的地方开始,同时定一个下表left 定义在i+1的位置上,定义下表right 在数组结尾的位置上。
98
+ 拿这个nums数组来举例,首先将数组排序,然后有一层for循环,i从下标0的地方开始,同时定一个下标left 定义在i+1的位置上,定义下标right 在数组结尾的位置上。
99
99
100
100
依然还是在数组中找到 abc 使得a + b +c =0,我们这里相当于 a = nums[i] b = nums[left] c = nums[right]。
101
101
102
- 接下来如何移动left 和right呢, 如果nums[i] + nums[left] + nums[right] > 0 就说明 此时三数之和大了,因为数组是排序后了,所以right下表就应该向左移动 ,这样才能让三数之和小一些。
102
+ 接下来如何移动left 和right呢, 如果nums[i] + nums[left] + nums[right] > 0 就说明 此时三数之和大了,因为数组是排序后了,所以right下标就应该向左移动 ,这样才能让三数之和小一些。
103
103
104
104
如果 nums[i] + nums[left] + nums[right] < 0 说明 此时 三数之和小了,left 就向右移动,才能让三数之和大一些,直到left与right相遇为止。
105
105
@@ -167,7 +167,7 @@ public:
167
167
168
168
如果不能,题意如何更改就可以使用双指针法呢? ** 大家留言说出自己的想法吧!**
169
169
170
- 两数之和 就不能使用双指针法,因为[ 1.两数之和] ( https://programmercarl.com/0001.两数之和.html ) 要求返回的是索引下表 , 而双指针法一定要排序,一旦排序之后原数组的索引就被改变了。
170
+ 两数之和 就不能使用双指针法,因为[ 1.两数之和] ( https://programmercarl.com/0001.两数之和.html ) 要求返回的是索引下标 , 而双指针法一定要排序,一旦排序之后原数组的索引就被改变了。
171
171
172
172
如果[ 1.两数之和] ( https://programmercarl.com/0001.两数之和.html ) 要求返回的是数值的话,就可以使用双指针法了。
173
173
Original file line number Diff line number Diff line change @@ -167,7 +167,33 @@ class Solution {
167
167
168
168
Python:
169
169
``` python
170
-
170
+ # 双指针法
171
+ class Solution :
172
+ def fourSum (self , nums : List[int ], target : int ) -> List[List[int ]]:
173
+
174
+ nums.sort()
175
+ n = len (nums)
176
+ res = []
177
+ for i in range (n):
178
+ if i > 0 and nums[i] == nums[i - 1 ]: continue
179
+ for k in range (i+ 1 , n):
180
+ if k > i + 1 and nums[k] == nums[k- 1 ]: continue
181
+ p = k + 1
182
+ q = n - 1
183
+
184
+ while p < q:
185
+ if nums[i] + nums[k] + nums[p] + nums[q] > target: q -= 1
186
+ elif nums[i] + nums[k] + nums[p] + nums[q] < target: p += 1
187
+ else :
188
+ res.append([nums[i], nums[k], nums[p], nums[q]])
189
+ while p < q and nums[p] == nums[p + 1 ]: p += 1
190
+ while p < q and nums[q] == nums[q - 1 ]: q -= 1
191
+ p += 1
192
+ q -= 1
193
+ return res
194
+ ```
195
+ ``` python
196
+ # 哈希表法
171
197
class Solution (object ):
172
198
def fourSum (self , nums , target ):
173
199
"""
You can’t perform that action at this time.
0 commit comments