0016_3Sum Closest

本文介绍了一种解决3SumClosest问题的高效算法,并通过示例代码详细展示了其实现过程。通过对数组排序并利用双指针技巧,该算法能够在O(n^2)的时间复杂度内找到与目标值最接近的三个数之和。

JAVA

在看过0015_3Sum的解题思路之后,本题作为练习,采用同样的思路进行运算。即使在看过3Sum之后,写代码时仍然有多处边界判断不准确,导致溢出或死循环。。。不过这种方法的效率还可以,大概排在前1/3左右。

public class Solution {
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int result = nums[0] + nums[1] + nums[2];
        int temp;
        for(int i = 0; i < nums.length - 2;){
            for(int j = i+1, k = nums.length - 1; j < k;){
                temp = nums[i] + nums[j] + nums[k];
                if(Math.abs(temp - target) <= Math.abs(result - target)){
                    result = temp;
                    if(Math.abs(temp - target) == 0){
                        return result;
                    }
                }
                if(temp < target){
                    ++j;
                    while(j < k && nums[j] == nums[j-1]){
                        ++j;
                    }
                }
                if(temp > target){
                    --k;
                    while(j < k && nums[k] == nums[k+1]){
                        --k;
                    }
                }
            }
            ++i;
            while(i < nums.length && nums[i] == nums[i-1]){
                ++i;
            }
        }
        return result;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值