lintcode-medium-3 Sum Closest

Posted 哥布林工程师

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了lintcode-medium-3 Sum Closest相关的知识,希望对你有一定的参考价值。

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.

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

思路和3 Sum基本一致,稍微有点变化而已。

public class Solution {
    /**
     * @param numbers: Give an array numbers of n integer
     * @param target : An integer
     * @return : return the sum of the three integers, the sum closest target.
     */
    public int threeSumClosest(int[] numbers ,int target) {
        // write your code here
        if(numbers == null || numbers.length == 0)
            return target;
        
        Integer result = null;
        Integer diff = null;
        Arrays.sort(numbers);
        
        for(int i = 0; i < numbers.length - 2; i++){
            if(i > 0 && numbers[i] == numbers[i - 1])
                continue;
            
            int left = i + 1;
            int right = numbers.length - 1;
            
            while(left < right){
                if(result == null){
                    result = numbers[i] + numbers[left] + numbers[right];
                    diff = Math.abs(numbers[i] + numbers[left] + numbers[right] - target);
                }
                
                if(Math.abs(numbers[i] + numbers[left] + numbers[right] - target) < diff){
                    result = numbers[i] + numbers[left] + numbers[right];
                    diff = Math.abs(numbers[i] + numbers[left] + numbers[right] - target);
                }
                
                if(numbers[i] + numbers[left] + numbers[right] < target){
                    left++;
                    while(left < right && numbers[left] == numbers[left - 1])
                        left++;
                }
                else if(numbers[i] + numbers[left] + numbers[right] > target){
                    right--;
                    while(left < right && numbers[right] == numbers[right + 1])
                        right--;
                }
                else
                    return target;
            }
        }
        
        return result;
    }
}

 

以上是关于lintcode-medium-3 Sum Closest的主要内容,如果未能解决你的问题,请参考以下文章

BZOJ 1116: [POI2008]CLO

[POI2008]CLO

bzoj1116 [POI2008]CLO

bzoj1116 [POI2008]CLO

1116: [POI2008]CLO

BZOJ 1116--CLO(并查集)