leetcode-16. 3Sum Closest

类似15题和18题的结合

题意:

给出一个数组和一个目标值,找出数组中的饿三个数,使他们的加和最接近target,输出和。(注意不是输出解)

我的思路:


  • 数组排序
  • 外层循环找第一个数
  • low = i + 1,high = len - 1
  • 如果sum == target, return target
  • 如果sum大于target,high–
  • 如果sum小于target,low++
  • 如果sum与target之差绝对值小于之前的绝对值,那么更新res= sum

注意:res初始为nums[0] + nums[1] + nums[2],不可为Integer.MAX_VALUE,否则计算res-target时若target为负则越界。
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int res = nums[0] + nums[1] + nums[2];
        for (int i = 0; i < nums.length - 2; i++) {
            int low = i + 1;
            int high = nums.length - 1;
            while (low < high) {
                int sum = nums[i] + nums[low] + nums[high];
                if (sum > target) {
                    high--;
                }
                else if(sum < target){
                    low++;
                }
                else return target;
                res = Math.abs(sum - target) < Math.abs(res - target) ? sum : res;
            }
        }
        return res;
    }

猜你喜欢

转载自blog.csdn.net/NNnora/article/details/81479894