@@ -25,13 +25,30 @@ using namespace std;
25
25
26
26
#define INT_MAX 2147483647
27
27
// 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
+ // ^ ^
28
46
int threeSumClosest (vector<int > &num, int target) {
29
-
30
-
47
+ // sort the array
31
48
sort (num.begin (), num.end ());
32
49
33
50
int n = num.size ();
34
- int distance = INT_MAX;
51
+ int distance = INT_MAX;
35
52
int result;
36
53
37
54
for (int i=0 ; i<n-2 ; i++) {
@@ -40,34 +57,38 @@ int threeSumClosest(vector<int> &num, int target) {
40
57
int a = num[i];
41
58
int low = i+1 ;
42
59
int high = n-1 ;
60
+ // convert the 3sum to 2sum problem
43
61
while ( low < high ) {
44
62
int b = num[low];
45
63
int c = num[high];
46
64
int sum = a+b+c;
47
65
if (sum - target == 0 ) {
48
66
// got the final soultion
49
67
return target;
50
- } else if (sum -target> 0 ) {
68
+ } else {
69
+
70
+ // tracking the minmal distance
51
71
if (abs (sum-target) < distance ) {
52
- distance = abs (sum - target);
72
+ distance = abs (sum - target);
53
73
result = sum;
54
74
}
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++;
62
86
}
63
- // skip the duplication
64
- while (low<n && num[low]==num[low+1 ]) low++;
65
- low++;
66
- }
87
+ }
67
88
}
68
89
}
69
- return result;
70
90
91
+ return result;
71
92
}
72
93
73
94
0 commit comments