讨论/《腾讯》 - 最接近的三数之和/
《腾讯》 - 最接近的三数之和
共 1 个回复

暴力暴力

    /**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
    var threeSumClosest = function(nums, target) {
    if (!nums || nums.length < 3) {
        return 0
    }

    nums.sort((a, b) => a > b ? 1 : -1)
    let min = Number.MAX_VALUE
    let minSum = Number.MAX_VALUE
    const len = nums.length
    for (let index = 0; index < len - 2; index ++) {
        let findex = index + 1;
        let lindex = findex + 1

        while (findex < len - 1) {
            while (lindex < len) {
                const sum = nums[index] + nums[findex] + nums[lindex]
                const diff = sum - target

                if (Math.abs(diff) < min) {
                    min = Math.abs(diff)
                    minSum = sum
                }
                lindex ++
            }
            findex ++ 
            lindex = findex + 1
        }
    }
    return minSum

};