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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69

#include <vector>
#include <algorithm>
#include <iostream>

using namespace std;


int threeSumClosest(vector<int> &num, int target) {
    int closest = MIN_INT;
    int diff = MAX_INT;    
    sort(num.begin(), num.end());

    size_t size = num.size();
    for (int i = 0; i < size; ++i)
    {
        int j = i+1;
        int k = size-1;
        while(j < k) 
        {
            int sum = num[i] + num[j] + num[k];
            int distance = abs(sum-target);
            if (distance < diff) 
            {
                closest = sum;
                diff = distance;
            }

            if (sum < target)
            {
                ++j
            }
            else
            {
                --k;
            }

            if (diff == 0) return closest;
        }
    }

    return results;
}

ostream & operator <<(ostream & out, vector<vector<int> > &vv)
{
    for (size_t i = 0; i < vv.size(); ++i)
    {
        vector<int> &v = vv[i];
        for (size_t j = 0; j < v.size(); ++j)
        {
            out << v[j] << ", ";
        }
        out << endl;
    }
    
    return out;
}

int main(int argc, char const *argv[])
{
    int a[] = {-1,0,1,2,-1,-4};
    int sa = sizeof(a)/sizeof(int);
    vector<int> va(a, a+sa);

    vector<vector<int> > result = threeSum(va);
    cout << result;

    return 0;
}
View Program Text


Test Status