1. 程式人生 > >[LeetCode] 16. 3Sum Closest Java

[LeetCode] 16. 3Sum Closest Java

leetcode i+1 each find ould for log temp 之前

題目: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).

分析:這道題目給了我們一個nums array 和一個 target, 讓我們找到一組三數之和,並且是最接近於target的。由於我們做過了三數之和,所以差不多是一樣方法來做這道題(這裏充分說明了,要老老實實順著題號做下去,較先的題目都可以被用來輔助之後的題)。方法就是先sort一下array,為啥要sort呢,因為要用到two pointers 來遍歷找兩數之和,只有在從小到大排序之後的結果上,才能根據情況移動left 和right。 當確定好了第一個數字後,就在剩下的array裏找兩數之和,在加上第一個數字,用這個temp_sum減去target 來得到temp_diff,如果temp_diff比之前的小,那麽更新diff 和 closestSum。 利用two pointers 特性, 如果temp_sum 比target 小的話,說明我們需要更大的sum,所以要讓left++以便得到更大的sum。 如果temp_sum 比target 大的話,我們就需要更小的sum。如果相等的話,直接return 就可以了。因為都相等了,那麽差值就等於0,不會有差值再小的了。

class Solution {
    public int threeSumClosest(int[] nums, int target) {
    
        int closeTarget = nums[0] + nums[1] + nums[2];
        Arrays.sort(nums);
        int minReduce = Math.abs(closeTarget - target);

        for(int i=0;i<nums.length-2;i++){
            int left = i+1,right = nums.length-1;
            
while(left < right){ int total = nums[left]+nums[right]+ nums[i]; if(total==target) return target; else if(total<target){ left++; }else right--; if(minReduce > Math.abs(total-target)){ minReduce = Math.abs(total - target); closeTarget = total; } } } return closeTarget; } }

[LeetCode] 16. 3Sum Closest Java