@@ -25,13 +25,30 @@ using namespace std;
2525
2626#define INT_MAX 2147483647
2727// solution: http://en.wikipedia.org/wiki/3SUM
28+ // the idea as blow:
29+ // 1) sort the array.
30+ // 2) take the element one by one, calculate the two numbers in reset array.
31+ //
32+ // notes: be careful the duplication number.
33+ //
34+ // for example:
35+ // [-4,-1,-1,1,2] target=1
36+ //
37+ // take -4, can cacluate the "two number problem" of the reset array [-1,-1,1,2] while target=5
38+ // [(-4),-1,-1,1,2] target=5 distance=4
39+ // ^ ^
40+ // because the -1+2 = 1 which < 5, then move the `low` pointer(skip the duplication)
41+ // [(-4),-1,-1,1,2] target=5 distance=2
42+ // ^ ^
43+ // take -1(skip the duplication), can cacluate the "two number problem" of the reset array [1,2] while target=2
44+ // [-4,-1,(-1),1,2] target=2 distance=1
45+ // ^ ^
2846int threeSumClosest (vector<int > &num, int target) {
29-
30-
47+ // sort the array
3148 sort (num.begin (), num.end ());
3249
3350 int n = num.size ();
34- int distance = INT_MAX;
51+ int distance = INT_MAX;
3552 int result;
3653
3754 for (int i=0 ; i<n-2 ; i++) {
@@ -40,34 +57,38 @@ int threeSumClosest(vector<int> &num, int target) {
4057 int a = num[i];
4158 int low = i+1 ;
4259 int high = n-1 ;
60+ // convert the 3sum to 2sum problem
4361 while ( low < high ) {
4462 int b = num[low];
4563 int c = num[high];
4664 int sum = a+b+c;
4765 if (sum - target == 0 ) {
4866 // got the final soultion
4967 return target;
50- } else if (sum -target> 0 ) {
68+ } else {
69+
70+ // tracking the minmal distance
5171 if (abs (sum-target) < distance ) {
52- distance = abs (sum - target);
72+ distance = abs (sum - target);
5373 result = sum;
5474 }
55- // skip the duplication
56- while (high>0 && num[high]==num[high-1 ]) high--;
57- high--;
58- } else {
59- if (abs (sum-target) < distance) {
60- distance = abs (sum - target);
61- result = sum;
75+
76+ if (sum -target> 0 ) {
77+ // skip the duplication
78+ while (high>0 && num[high]==num[high-1 ]) high--;
79+ // move the `high` pointer
80+ high--;
81+ } else {
82+ // skip the duplication
83+ while (low<n && num[low]==num[low+1 ]) low++;
84+ // move the `low` pointer
85+ low++;
6286 }
63- // skip the duplication
64- while (low<n && num[low]==num[low+1 ]) low++;
65- low++;
66- }
87+ }
6788 }
6889 }
69- return result;
7090
91+ return result;
7192}
7293
7394
0 commit comments