其他分享
首页 > 其他分享> > 剑指offer 最接近的三数之和

剑指offer 最接近的三数之和

作者:互联网

力扣题目链接
6ms有点长也不知道咋优化

class Solution {
    public int threeSumClosest(int[] nums, int target) {
        int n = nums.length;
        //先排个序
        Arrays.sort(nums);
        //记录第一个值
        int ans = nums[0] +nums[1] + nums[2];

        for(int i=0;i<n;i++){
            int l = i+1,r = n-1;
            while(l<r){
                int sum = nums[i] + nums[l] +nums[r];
                if(Math.abs(target-sum) < Math.abs(target-ans)) ans = sum;
                if(sum < target) l++;
                else if(sum > target) r--;
                else 
                return ans;
            }
        }
        return ans;
    }
}

标签:return,target,nums,int,三数,offer,ans,接近
来源: https://www.cnblogs.com/jianjiana/p/15862355.html