leetcode 16 3Sum Closest

題目詳情

Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

給定一個整數數組,咱們須要找出數組中三個元素的加和,使這個加和最接近於輸入的target數值。返回這個最接近的加和。題目假設一道題只有一個答案。算法

For example,輸入數組S = {-1 2 1 -4},目標和target = 1.
最接近target的加和是 2. (-1 + 2 + 1 = 2).數組

想法

  • 這道題和第15題很像,因此這道題也能夠選擇預排序算法。
  • 咱們先對數組進行預排序。
  • 而後經過減治思想,咱們先鎖定第一個元素,以後找兩個元素的加和儘量接近target和第一個元素值的差值。
  • 找後兩個元素的時候,使用左右指針從兩端查找。

解法

public int threeSumClosest(int[] nums, int target) {
        int min = Integer.MAX_VALUE;
        Arrays.sort(nums);
        
        for(int i=0;i<nums.length-2;i++){
            int temp = target - nums[i];
            int low = i+1;
            int high = nums.length-1;           
            while(low < high){
                int diff =   nums[low]+nums[high]-temp;
                if(diff == 0) return target;
                if(Math.abs(min) > Math.abs(diff)){
                    min = diff;
                    }
                if(diff > 0)high--;
                else low++;
                    
            }
        }
        
        return target+min;
    }
相關文章
相關標籤/搜索