Friday, February 27, 2015

3Sum Closest

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


--------------- thinking --------------------------------------
using shifting method to adjust the location, and find the closest sum target
---------------codes --------------------------------
class Solution {
public:
    int threeSumClosest(vector<int> &num, int target) {
        sort(num.begin(), num.end());
        int start = 0;
        int end = num.size() - 1;
        int diff = INT_MAX;
        //it's very important to stop when star is next to end(start+1<end), because there will be no 3 items left anymore!!!!!
        while (start+1 < end && start >= 0 && end < num.size()) {
            //bug here -> remember the start and end have been considered, so start+1, end-1 should be used as input
            int nearest_ele = findNearest(num, start+1, end-1, target - num[start] - num[end]);
            int sum = nearest_ele + num[start] + num[end];
            if (abs(sum - target) < abs(diff)) {
                diff = sum - target;
            }
            //when the sum is smaller than target, move start item
            if (sum - target < 0) {
                start++;
            } else if (sum - target > 0) {//when the snum is bigger than target, move end item
                end--;
            } else {
                return target;
            }
        }
        return target + diff;
    }
    //binary search to find the nearest item to the target!
    int findNearest(vector<int> &num, int start, int end, int target) {
        //bug here
        //remember to check if target is inside of start and end
        if (num[start] >= target) {
            return num[start];
        }
        if (num[end] <= target) {
            return num[end];
        }
        while (start + 1 < end) {
            int mid = start + (end - start) / 2;
            if (num[mid] < target) {
                start = mid;
            } else {
                end = mid;
            }
        }
        if (num[start] >= target) {
            return num[start];
        }
        if (num[end] <= target) {
            return num[end];
        }
        return abs(num[start] - target) < abs(num[end] - target) ? num[start] : num[end];
    }
};

No comments:

Post a Comment