leetcode 1016. 最接近的三数之和

class Solution {
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
		//使用Integer.MAX_VALUE会报错,溢出
        int res = 10000;
        for (int i = 0; i < nums.length; i++) {
            if (i > 0 && nums[i] == nums[i - 1]) continue;
            int j = i + 1;
            int k = nums.length - 1;
            while (j < k) {
                int r = nums[i] + nums[j] + nums[k];
                if (Math.abs(r - target) < Math.abs(res - target)){
                    res= r;
                }
                if (r == target) return r;
                else if (r > target) {
                    k--;
                } else {
                    j++;
                }
            }
        }
        return res;
    }
}

 

©️2020 CSDN 皮肤主题: 书香水墨 设计师:CSDN官方博客 返回首页