[LeetCode]016. 3Sum 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. 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).

Solution: similar method to 3sum, but don't need to consider the duplicate numbers here.

Running Time: O(n*n);

create a variable named "min_value" to store the minimal difference between the target and the 3 sum,

if the |target - sum| < min_value, min_value = |target - sum|; 


这里不需要消除重复的数字(内外循环皆不需要)。



public class Solution {
    public int threeSumClosest(int[] num, int target) {
        // Start typing your Java solution below
        // DO NOT write main() function
        Arrays.sort(num);
        int len = num.length;
        int min_value = Integer.MAX_VALUE;
        int result = 0;
        //the distance between 3sum and the target;
        for(int i=0; i<len; i++){
            int start = i + 1;
            int end = len - 1;
            while(start<end){
                int sum = num[i] +num[start]+num[end];
                if(sum == target){
                    min_value = 0;
                    result = sum;
                    break;
                }else if(sum < target){
                    if(target - sum < min_value){
                        min_value = target - sum;
                        result = sum;
                    }
                    start++;
                }else{
                    if(sum - target < min_value){
                        min_value = sum - target;
                        result = sum;
                    }
                    end--;
                }
            }
        }
        return result;
    }
}


你可能感兴趣的:(LeetCode)