File tree 1 file changed +49
-0
lines changed
1 file changed +49
-0
lines changed Original file line number Diff line number Diff line change
1
+ <!DOCTYPE html>
2
+ < html lang ="en ">
3
+ < head >
4
+ < meta charset ="UTF-8 " />
5
+ < meta name ="viewport " content ="width=device-width, initial-scale=1.0 " />
6
+ < title > Document</ title >
7
+ </ head >
8
+ < body >
9
+ < script >
10
+ // 解法:排序 + 双指针
11
+ // 1.首先对数组进行排序,排序后固定一个数 nums[i],再使用左右指针指向 nums[i]后面的两端,数
12
+ // 字分别为 nums[L] 和 nums[R],计算三个数的和 sum 判断是否满足为 0,满足则添加进结果集
13
+ // 2.如果 nums[i] 大于 0,则三数之和必然无法等于 0,结束循环
14
+ // 3.如果 nums[i] == nums[i−1],则说明该数字重复,会导致结果重复,所以应该跳过
15
+ // 4.当 sum == 0 时,nums[L] == nums[L+1] 则会导致结果重复,应该跳过,L++
16
+ // 5.当 sum == 0 时,nums[R] == nums[R−1] 则会导致结果重复,应该跳过,R−−
17
+ // 6.时间复杂度:O(n^2) n 为数组长度
18
+
19
+ /**
20
+ * @param {number[] } nums
21
+ * @return {number[][] }
22
+ */
23
+ var threeSum = function ( nums ) {
24
+ let ans = [ ] ;
25
+ const len = nums . length ;
26
+ if ( nums == null || len < 3 ) return ans ;
27
+ nums . sort ( ( a , b ) => a - b ) ; // 排序
28
+ for ( let i = 0 ; i < len ; i ++ ) {
29
+ if ( nums [ i ] > 0 ) break ; // 如果当前数字大于0,则三数之和一定大于0,所以结束循环
30
+ if ( i > 0 && nums [ i ] == nums [ i - 1 ] ) continue ; // 去重
31
+ let L = i + 1 ;
32
+ let R = len - 1 ;
33
+ while ( L < R ) {
34
+ const sum = nums [ i ] + nums [ L ] + nums [ R ] ;
35
+ if ( sum == 0 ) {
36
+ ans . push ( [ nums [ i ] , nums [ L ] , nums [ R ] ] ) ;
37
+ while ( L < R && nums [ L ] == nums [ L + 1 ] ) L ++ ; // 去重
38
+ while ( L < R && nums [ R ] == nums [ R - 1 ] ) R -- ; // 去重
39
+ L ++ ;
40
+ R -- ;
41
+ } else if ( sum < 0 ) L ++ ;
42
+ else if ( sum > 0 ) R -- ;
43
+ }
44
+ }
45
+ return ans ;
46
+ } ;
47
+ </ script >
48
+ </ body >
49
+ </ html >
You can’t perform that action at this time.
0 commit comments