Tcdian / keep

今天不想做,所以才去做。
MIT License
5 stars 1 forks source link

16. 3Sum Closest #230

Open Tcdian opened 4 years ago

Tcdian commented 4 years ago

16. 3Sum Closest

给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。

Example

Input: nums = [-1,2,1,-4], target = 1
Output: 2
Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

Note

Tcdian commented 4 years ago

Solution

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number}
 */
var threeSumClosest = function(nums, target) {
    const sortedNums = [...nums].sort((a, b) => a - b);
    let result = Infinity;
    let difference = Infinity;
    for (let i = 0; i < sortedNums.length - 2; i++) {
        let left = i + 1;
        let right = sortedNums.length - 1;
        while (left < right) {
            if (left > i + 1 && sortedNums[left] === sortedNums[left - 1]) {
                left++;
                continue;
            }
            if (right < sortedNums.length - 1 && sortedNums[right] === sortedNums[right + 1]) {
                right--;
                continue;
            }
            const sum = sortedNums[left] + sortedNums[right] + sortedNums[i];
            if (Math.abs(sum - target) < difference) {
                difference = Math.abs(sum - target);
                result = sum;
            }

            if (sum === target) {
                return sum;
            } else if (sum < target) {
                left++;
            } else {
                right--;
            }
        }
    }
    return result;
};
function threeSumClosest(nums: number[], target: number): number {
    const sortedNums = [...nums].sort((a, b) => a - b);
    let result = Infinity;
    let difference = Infinity;
    for (let i = 0; i < sortedNums.length - 2; i++) {
        let left = i + 1;
        let right = sortedNums.length - 1;
        while (left < right) {
            if (left > i + 1 && sortedNums[left] === sortedNums[left - 1]) {
                left++;
                continue;
            }
            if (right < sortedNums.length - 1 && sortedNums[right] === sortedNums[right + 1]) {
                right--;
                continue;
            }
            const sum = sortedNums[left] + sortedNums[right] + sortedNums[i];
            if (Math.abs(sum - target) < difference) {
                difference = Math.abs(sum - target);
                result = sum;
            }

            if (sum === target) {
                return sum;
            } else if (sum < target) {
                left++;
            } else {
                right--;
            }
        }
    }
    return result;
};