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.

    For example, given array S = {-1 2 1 -4}, and target = 1.

    The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

分析:

找出與給出的target最接近的三個數的和。類似於3Sum,也是先排序後遍歷配合左右遊標[O(N^2)],使用abs函數判斷當前解和最優解與target的距離來對最優解進行調整,對於遊標的移動,如果和小於target則左遊標右移,大於則右遊標左移。

Java

class Solution {
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int ans = nums[0] + nums[1] + nums[2];
        for(int i = 0; i < nums.length; i++){
            int temp = target - nums[i];
            int j = i + 1, k = nums.length - 1;
            while(j < k){
                if(Math.abs(target - ans) > Math.abs(temp - nums[j] - nums[k])){
                    ans = nums[i] + nums[j] + nums[k];
                    if( ans == target) return target;
                }
                if(temp - nums[j] - nums[k] < 0) 
                    k--;
                else 
                    j++;
            }
        }
        return ans;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章