Friday, February 22, 2013

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).
*/
class Solution {
public:
    int abs(int value){
      if(value<0) return (-1)*value;
      return value;
    }
    int distance(int src, int target){
      return abs(src-target);
    }
    int getClosest(vector<int> num, int end, int target){
        if(end==2) return num.at(2)+num.at(1)+num.at(0);
        int result;
        result = getClosest(num,end-1,target);
        int i,j;
        int sum;
        for(i=0;i<end;i++){
          for(j=0;j<end&&j!=i;j++){
             sum = num.at(i)+num.at(j)+num.at(end);
             if (distance(sum, target)<distance(result, target)){
               result = sum;
             }
          }
        }
        return result;
    }
    int threeSumClosest(vector<int> &num, int target) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int size = num.size();
        if(size<3) return 0;
        return getClosest(num, size-1, target);
    }
};

No comments:

Post a Comment