Day twenty: force buckle 15, the sum of three numbers

Address: leetcode-cn.com/problems/3s…

I’m going to try to solve the problem by sorting and double pointer. I’m going to try to solve it by sorting and double pointer.

Sort the array starting from the left, select one value as the constant value, solve the right, get the two values that add to 0, similar to quicksort, define the first and the last, add to the constant value equal to 0 record these three values. Less than 0, head moves right; Greater than 0, the tail moves to the left. Finally, move the fixed value to the right and repeat the procedure.

var threeSum = function(nums) { nums.sort((a,b) => a - b); // sort let I = 0; let res = []; If (nums[0] <= 0 && nums[nums.length-1] >= 0) {while(I < nums.length-2) {let left = I + 1; let right = nums.length - 1; While (left < right) {if(nums[right] < 0)// Filter {break; } if(nums[i] + nums[left] + nums[right] === 0) { res.push([nums[i],nums[left],nums[right]]); // fill in while (nums[left] === nums[++left]) {}} else if(nums[I] + nums[left] + nums[right] < 0) {while (nums[left] === = Nums [+ + left]) {} / / prevent overlap} else {while (nums = = = [right] nums [-- right]) {} / / prevent overlap}} while (nums = = = [I] nums [+ + I]) {} / / prevent overlap  } } return res; };Copy the code
Execution time: 180 ms, beating 46.17% of all JavaScript commits
Memory consumption: 47.8 MB, beating 30.60% of all JavaScript commits