16. 3Sum Closest

Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

Example:

Given array nums = [-1, 2, 1, -4], and target = 1.

The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

这题可以用暴力做,但时间复杂度是n^3的

还有一种方法是首尾指针逼近法:根据三个数的和来决定left和right的移动,效率比暴力高些

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number}
 */
var threeSumClosest = function(nums, target) {
    nums.sort((x, y) => x - y)
    let close = Infinity
    let len = nums.length
    for(let i = 0; i < len - 2; i ++) {
        let left = i + 1
        let right = len - 1
        while(left < right) {
            let res = nums[i] + nums[left] + nums[right]
            let cha = Math.abs(res - target)
            let cha2 = Math.abs(close - target)
            if(cha < cha2) close = res
            if(res - target < 0) left ++
            else if(res - target > 0) right --
            else return target
        }
    }
    return close
};

暴力:

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number}
 */
var threeSumClosest = function(nums, target) {
    let len = nums.length
    let res = 0, ans = 0
    let close = Infinity
    for(let i = 0; i < len - 2; i ++) {
        for(let j = i + 1; j < len - 1; j ++) {
            for(let z = j + 1; z < len; z ++) {
                res = nums[i] + nums[j] + nums[z]
                if(close > Math.abs(res - target)) {
                    close = Math.abs(res - target)
                    ans = res
                    if(!close) return target
                }
            }
        }   
    }
    return ans
};

an hour age 和 10 minutes ago 都是用暴力做的,区别仅仅是加了差值为0时,直接return target这个特判,没想到就快了很多

a few seconds ago是用首尾指针逼近做的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值