1. 程式人生 > >leetcode-16. 3Sum Closest

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; }