leetcode-15三数之和

101 阅读1分钟

题目:

给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。

image.png leetcode: leetcode-cn.com/problems/3s…

解题思路:

  1. 先对数组进行排序
  2. 从0到length-2遍历数组(i到倒数第二个时,start是倒数第一个,所以为了防止end越界)
  3. 在进行下一轮时,如果当前数字等于前一数字,则跳过这个数(去重,因为题干要求不可以重复)
  4. 如果数字不同,则设置start= i+1,end=length-1,查看i,start end 与0比较,
  5. 比0小 start++ 比0大 end-- 等于0 加入结果result数组中(同时start++继续查找)

c1050fde33801d79643ce650b020ce3.jpg先对数组

JavaScript代码:

var threeSum = function(nums) {
    // 存放结果
    const result = [];
    // 对数组进行排序
    nums.sort(function(a, b) {
            return a - b;
        })
        // 控制遍历次数,i为倒数第二个时结束
    for (let i = 0; i < nums.length - 2; i++) {
        // i循环时如果当前数字等于前一数字,则跳过这个数
        if (i === 0 || nums[i] !== nums[i - 1]) {
            let start = i + 1,
                end = nums.length - 1;
            // 结束遍历条件
            while (start < end) {
                // 找到和为零的三个数,存放结果,并继续向中间找
                if (nums[i] + nums[start] + nums[end] === 0) {
                    result.push([nums[i], nums[start], nums[end]]);
                    start++;
                    end--;
                    // 对相邻相等的数字再排除一次
                    while (start < end && nums[start] === nums[start - 1]) {
                        start++;
                    }
                    while (start < end && nums[end] === nums[end + 1]) {
                        end--;
                    }
                }
                // 和小于零start++  ,使得和逐渐变大
                else if (nums[i] + nums[start] + nums[end] < 0) {
                    start++;
                    // 和大于0 end-- ,使得和逐渐变小
                } else {
                    end--
                }
            }
        }
    }
    return result;
};
let nums = [-1, 0, 1, 2, -1, -4]
result = threeSum(nums)
console.log(result);