3SumClosest

原题地址:https://leetcode.com/problems/3sum-closest/#/description

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

思路:
这道题课3sum类似,只是在判断条件上有所不同。当curr和target的diff比rst和target之间diff小的时候才会更新rst。去重和3sum是一样的。

代码:


public int threeSumClosest(int[] nums, int target) {
    if(nums == null || nums.length <= 2){
        return 0;
    }
    int rst = Integer.MAX_VALUE / 2;
    Arrays.sort(nums);
    for(int i = 0; i <= nums.length - 3; i++){
        while(i != 0 && nums[i - 1] == nums[i] && i <= nums.length - 3){
            i++;
        }
        int j = i + 1;
        int k = nums.length - 1;
        int curr = nums[i] + nums[j] + nums[k];
        if(Math.abs(curr - target) < Math.abs(rst - target)){
            rst = curr;
            j++;
            k--;
            while(j < k && nums[j - 1] == nums[j]){
                j++;
            }
            while(j < k && nums[k + 1] == nums[k]){
                k--;
            }
        }
        else if(curr < target){
            j++;
        }
        else{
            k--;
        }
    }
    return rst;
}

Comments

Popular Posts