Monday, November 25, 2013

LeetCode Problem : 3Sum Closest

Problem

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

Code

int bin_search(const vector<int>& A,int left,int right,int target)
{
    int min_diff = INT_MAX;
    while(left <= right){
        int mid = (left + right)/2;
        int diff = A[mid - 1] - target;
        if(diff == 0)
            return 0;
        if(diff < 0)
            left = mid + 1;
        else
            right = mid - 1;
        if(abs(min_diff) > abs(diff))
            min_diff = diff;
    }
    return min_diff;
}
int threeSumClosest(vector<int> &num, int target) {
    // Note: The Solution object is instantiated only once and is reused by each test case.
    int n = num.size();
    int min_diff = INT_MAX;
    sort(num.begin(),num.end());
    for(int i = 0;i < n - 2;++i){
        for(int j = i + 1;j < n - 1;++j){
            int k = j + 1;
            int newtarget = target - (num[i] + num[j]);
            int diff = bin_search(num,k + 1,n,newtarget);
            if(abs(min_diff) > abs(diff))
                min_diff = diff;
        }
    }
    return  target + min_diff;
}

No comments:

Post a Comment