[LC] 16. 3Sum Closest

时间:2020-03-04 12:56:34   收藏:0   阅读:78

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).

class Solution {
    public int threeSumClosest(int[] nums, int target) {
        int globalMin = Integer.MAX_VALUE;
        int res = globalMin;
        if (nums == null || nums.length == 0) {
            return res;
        }
        Arrays.sort(nums);
        for (int i = 0; i < nums.length - 2; i++) {
            // skip i as well
            if (i > 0 && nums[i - 1] == nums[i]) {
                continue;
            }
            int j = i + 1, k = nums.length - 1;
            // j and k cannot meet since may add the same number twice
            while (j < k) {
                int sum = nums[i] + nums[j] + nums[k];
                if (sum < target) {
                    if (target - sum < globalMin) {
                        globalMin = target - sum;
                        res = sum;
                    }
                    j+=1;
                } else {
                    if (sum - target < globalMin) {
                        globalMin = sum - target;
                        res = sum;
                    }
                    k-=1;
                }
            }
        }
        return res; 
    }
}

 

原文:https://www.cnblogs.com/xuanlu/p/12408543.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!