Monday, 22 August 2016

3Sum Closest

Given an array A of n integers, find three integers in A such that the sum is closest to a given value. Return the sum of the three integers. You may assume that each input would have exactly one solution.
It is a modified version of the problem 3 Sum
    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).


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {
        //sort the vector
        sort(nums.begin(), nums.end());
        int temp = 0, j, k, diff = INT_MAX, out = 0;
        for(int i = 0; i < nums.size(); i++){
            j = i + 1;
            k = nums.size() - 1;
            while(j < k){
                temp = nums[i] + nums[j] + nums[k];
                //update the minimum diff till now and store the output 
                if(abs(temp - target) < diff){
                    diff = abs(temp - target);
                    out = temp;
                }
                //if diff is 0, return the output else increment or decrement based on the current (temp - target) value
                if(diff == 0){
                    return out;
                }else if(temp - target < 0){
                    j++;
                }else{
                    k--;
                }
            }
        }
        return out;
    }
};
Share:

0 comments:

Post a Comment

Contact Me

Name

Email *

Message *

Popular Posts