-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path15.三数之和.js
42 lines (38 loc) · 1.02 KB
/
15.三数之和.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/*
* @lc app=leetcode.cn id=15 lang=javascript
*
* [15] 三数之和
*/
// @lc code=start
/**
* @param {number[]} nums
* @return {number[][]}
*/
var threeSum = function(nums) {
let res = [];
nums.sort((a,b)=> a - b);
for(let i = 0; i < nums.length; i++){
let a = nums[i];
let lo = i + 1;
let hi = nums.length - 1;
if( nums[i] === nums[i-1])continue
while(lo < hi) {
let value = a + nums[lo] + nums[hi];
if(value === 0){
res.push([a,nums[lo], nums[hi]])
while(lo < hi && nums[lo] === nums[lo + 1]) lo++;
while(lo < hi && nums[hi] === nums[hi - 1]) hi--;
lo++;
hi--;
}else if(value > 0) {
while(lo < hi && nums[hi] === nums[hi - 1]) hi--;
hi--;
}else if(value < 0) {
while(lo < hi && nums[lo] === nums[lo + 1]) lo++;
lo++;
}
}
}
return res;
};
// @lc code=end