LeetCode16. 3Sum Closest 三數之和改

16.3Sum Closest最接近目標值的三數之和

3Sum Closest

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

Example:

Given array nums = [-1, 2, 1, -4], and target = 1.

The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
基於三數之和的修改

解決問題的思路和LeetCode15 3Sum三數之和是一致的,只不過在處理的時候有所不同。同樣採用的也是雙指針的方式。在每次指針移動的時候都要去比較目前的值到目標值的距離和之前最近的值到距離的大小,記錄最接近目標值用於下一次進行比較。

class Solution {
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int numsLen = nums.length;
        int result = nums[0] + nums[1] + nums[2];
        for(int i = 0 ; i < numsLen - 2; i++){
            if(i > 0 && nums[i] == nums[i-1]){
                continue;
            }            
            int left = i+ 1;
            int right = nums.length -1;
            while(left < right){
                int sum = nums[i] + nums[left] + nums[right];
                if(sum < target){
                    if(Math.abs(target - sum) < Math.abs(target - result)){
                        result = sum;
                    }
                    left++;
                 while(left < right && nums[left] == nums[left - 1]){
                    left++;
                }
                } else if(sum > target){
                    if(Math.abs(target - sum) < Math.abs(target - result)){
                        result = sum;
                    }
                    right--;
                while(left < right && nums[right] == nums[right + 1]){
                    right--;
                }
                } else {
                    return target;
                }
            }
        }
        return result;
    }
}
發佈了37 篇原創文章 · 獲贊 8 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章