leetcode 3Sum. 处理特殊状况+哈希思想

Given an array nums of n integers, are there elements a, b, c in nums
such that a + b + c = 0? Find all unique triplets in the array which
gives the sum of zero.优化

Note:指针

The solution set must not contain duplicate triplets.code

Example:排序

Given array nums = [-1, 0, 1, 2, -1, -4],three

A solution set is: [ [-1, 0, 1], [-1, -1, 2] ]ip

和TwoSum整体思想差很少,可是要多一层外循环,枚举每个target的值,target的值为0-nums[i], 咱们能够作一些优化在减小遍历次数:
1.正数直接跳出,由于排序后后面的确定都是正数
2.和前一个数相同的值能够直接continueelement

注意几种特殊状况[-1,0,1,2,-1,-4],排序后为[-4,-1,-1,0,1,2],[-2,0,0,2,2],push的时候判断下左指针和右指针与上个位置的是否相等,注意这里的条件是或,若是有一个不相等,且值和为target便可pushget

/**
 * @param {number[]} nums
 * @return {number[][]}
 */
var threeSum = function(nums) {
  let ans = [];
  nums.sort((a,b) => a-b || -1);
  let len = nums.length;
  for(let i = 0; i < len; i++) {
      if(nums[i] > 0)
          break;
      if(i>0 && nums[i]===nums[i-1])
          continue;
      let target = 0 - nums[i];
      let l = i+1,r=len-1;

      while(l<r) {
          if(nums[l]+nums[r]===target && (((l-1>=0)&&nums[l]!==nums[l-1])||(nums[r]!==nums[r+1]&&(r+1<=len))) ) {
              let t = [];
              t.push(nums[i],nums[l],nums[r]);
              ans.push(t);
              l++;
              r--;
          }else if(nums[l]+nums[r]<target) {
              l++;
          }else if(nums[l]+nums[r]>target) {
              r--;
          }else {
              l++;
              r--;
          }
      }
  }
  return ans;
};

console.log(threeSum([-1,0,1,2,-1,-4]));
相关文章
相关标签/搜索