最后一遍-L16-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 1:

Input: nums = [-1,2,1,-4], target = 1
Output: 2
Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
 

Constraints:

3 <= nums.length <= 10^3
-10^3 <= nums[i] <= 10^3
-10^4 <= target <= 10^4

Array two index,理解题目的意思

代码:

// 方法一和方法二,哪一个耗时更高?

// 方法一
public static int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        Integer result = Integer.MAX_VALUE;
        //two point interation
        for (int i = 0; i < nums.length - 2; i++) {
            if(i > 0 && nums[i] == nums[i-1]) continue;
            int j=i+1,k=nums.length-1;
            while(j < k){
                if(j>i+1 && nums[j-1] == nums[j]){
                    j++;
                    continue;
                }
                int sum = nums[i]+nums[j]+nums[k];
                if(sum == target){
                    return target;
                }else if(sum < target){
                    j++;
                   if( Math.abs(sum-target) < Math.abs(result-target)){
                    result=sum;
                    }
                    
                }else{
                    k--;
                   if(Math.abs(sum-target) < Math.abs(result-target)){
                    result=sum;
                }
                }
            }
        }
        return result;
    }
    
// 方法二

public static int threeSumClosest(int[] nums, int target) {
        Integer result = 0;
        Integer distance = Integer.MAX_VALUE;
        Arrays.sort(nums);
        for (int i = 0; i < nums.length; i++) {
            // skip same elements
            if(i>0 && nums[i-1] == nums[i]) continue;
            int j = i+1;int k = nums.length-1;
            while(j < k){
                if(j>i+1 && nums[j-1] == nums[j]){
                    j++;
                    continue;
                }
                int tmpSum = nums[i]+nums[j]+nums[k];
                if(tmpSum == target){
                    return target;
                }else if(tmpSum < target){
                    j++;
                    int compare = Math.abs(target-tmpSum);
                    if(compare < distance) {
                        distance= compare;
                        result = tmpSum;
                    }
                }else{
                    k--;
                    int compare = Math.abs(target-tmpSum);
                    if(compare < distance) {
                        distance= compare;
                        result = tmpSum;
                    }
                }

            }
        }
        return result;
    }
    

Powered by andiHappy and Theme by AndiHappy