leetcode 16 最接近的三数之和

版权声明:copy-right:BHY https://blog.csdn.net/WallBreakerBhy/article/details/84197147

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

例如,给定数组 nums = [-1,2,1,-4], 和 target = 1.

与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2).

显然,时间复杂度为O(n^3)的算法就没必要考虑了,笔试或面试的时候如果写了O(n^3)的应该也过不了吧。

可以先把数组排序,先取第一个数为nums[i],然后在剩下的数里选两个,由于数组已经排好序,可以用双指针法,l=i+1;r=nums.length-1;然后判断nums[i]+nums[l]+nums[r]与target的差值,如果比原来的小则更新。

如果nums[i]+nums[l]+nums[r]<target,则l++;如果nums[i]+nums[l]+nums[r]>target,则r--;

class Solution {
    public int threeSumClosest(int[] nums, int target) {
        if(nums.length<3){
            return -1;
        }
        Arrays.sort(nums);
        int res=nums[0]+nums[1]+nums[2];
        for(int i=0;i<nums.length-1;i++){
            int l=i+1;
            int r=nums.length-1;
            while(l<r){
                int tmp = nums[i]+nums[l]+nums[r];
                if(Math.abs(target-tmp)<Math.abs(target-res)){
                    res=tmp;
                }
                if(tmp<target){
                    l++;
                }
                else if(tmp>target){
                    r--;
                }
                else{
                    return tmp;
                }
            }
        }
        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/WallBreakerBhy/article/details/84197147