leetcode 57: 3Sum Closest

3Sum ClosestJan 18 '12

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


class Solution {
public:
    int threeSumClosest(vector<int> &num, int target) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(num.size()<3) return 0;
        
        int min=num[0]+num[1]+num[2];
        sort(num.begin(), num.end() );
        int sz=num.size();
        int j,k;
        for(int i=0; i<sz-2;i++) {
            j=i+1;
            k=sz-1;
            while(j<k) {
                int sum = num[i]+num[j]+num[k];
                int temp = sum-target;
                if( temp == 0 ) return target;
                else if( temp < 0 ) j++;
                else k--;
                
                if( abs( temp ) < abs(min - target) ) min = sum;
            }
        }
        
        return min;
    }
};

public class Solution {
    
// null     
    public int threeSumClosest(int[] num, int target) {
        // Start typing your Java solution below
        // DO NOT write main() function
        
        // initial check.
        //if( num==null || num.length<3) return 0;//throw new Exception("wrong input. must be at least 3 integers."); 
        int sz = num.length;
    
        Arrays.sort( num );
        
        int min = Integer.MAX_VALUE;  // pay attention. min's initial value should be MAX_VALUE.
        int gsum = 0;    // since two possible sum (+-target) exist, we need gsum to record which sum.
        for(int i=0; i<sz-2; i++) {
            int j=i+1, k=sz-1;
            
            while(j<k) {
                int sum = num[i] + num[j] + num[k];
                int x = Math.abs(sum-target);
                if(x<min) {
                    min = x;
                    gsum = sum;
                }
                
                if(sum==target) {
                    ++j;
                    --k;
                    return sum;
                } else if( sum<target) {
                    ++j;
                } else {
                    --k;
                }
            }
        }
        
        return gsum;
    }
}


posted @ 2013-01-27 14:06  西施豆腐渣  阅读(112)  评论(0编辑  收藏  举报