Skip to content

Latest commit

 

History

History
44 lines (43 loc) · 1.19 KB

015-3sum.md

File metadata and controls

44 lines (43 loc) · 1.19 KB

双指针解决问题 通过两个for循环,固定i下标 left,right两个指针寻找解

/**
 * @param {number[]} nums
 * @return {number[][]}
 */
不做去重版本
 var threeSum = function(nums) {
    nums = nums.sort((a, b) => a - b);
    console.log(nums)
    let result = new Set();
    for (let i = 0; i < nums.length - 2; i++) {
        if (nums[i] > 0) {
            return Array.from(result).map(i => i.split(','));
        }
        if (i > 0 && nums[i] === nums[i - 1]) {
            continue;
        }
        let cur = nums[i];
        let left = i + 1;
        let right = nums.length - 1;
        while(left < right) {
            let sum = cur + nums[left] + nums[right];
            if (sum < 0) {
                left++
                continue;
            } else if (sum > 0) {
                right--;
                continue;
            } else {
                // res.push([cur, nums[left], nums[right]]);
                result.add(`${cur},${nums[left]},${nums[right]}`);
                console.log(i, [cur, nums[left], nums[right]])
                right--;
                left++;
            }
        }
    }
    return Array.from(result).map(i => i.split(','));
};