leetcode-Medium-15期-3Sum

作者: 石头说钱 | 来源:发表于2019-03-14 22:21 被阅读4次

题目

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.

从整数数组中找出三个数加起来等0,不能返回重复的

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

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

由于数组中有可能存在重复的数,在排序后的数组中,它们是连在一起的,那么当找到第一对数值对的时候,继续找的时候,要判断下一个位置的数是否跟当前位置的置相同,如果相同,可忽略,因为这个值同样满足条件,但是其会造成重复的组合

var threeSum = function(nums) {
    const triplets = [];
  if (nums.length < 3) {
    return triplets;
  }
  nums.sort((a, b) => (a - b));
  for (let i = 0; i < nums.length - 2; i++) {
    let a = nums[i];
    // 防止重复的两个数连在一起,取到重复的结果,
     if (nums[i - 1] !== undefined && nums[i] === nums[i - 1]) {
       continue; // 相当于return,不会执行下面代码
     }
    let left = i + 1;
    let right = nums.length - 1;
    while (left < right) {
      let b = nums[left];
      let c = nums[right];
      let sum = a + b + c;
      if (sum === 0) {
        triplets.push([a, b, c]);
        while (nums[left] === nums[left + 1]) {
          left++;
        }
        while (nums[right] === nums[right - 1]) {
          right--;
        }
        left++;
        right--;
      } else if (sum > 0) {
        right--;
      } else {
        left++;
      }
    }
  }
  return triplets;
};
  • 关键
  if (nums[i - 1] !== undefined && nums[i] === nums[i - 1]) {
       continue;
     }

[-1,0,1,2,-1,-4] // 排序后变成[-4, -1, -1, 0, 1 ,2]

不加上面代码结果:
[[-1,-1,2],[-1,0,1],[-1,0,1]]

加上面代码结果:
[[-1,-1,2],[-1,0,1]]

相关文章

网友评论

    本文标题:leetcode-Medium-15期-3Sum

    本文链接:https://www.haomeiwen.com/subject/bcnapqtx.html