File tree Expand file tree Collapse file tree 2 files changed +31
-1
lines changed Expand file tree Collapse file tree 2 files changed +31
-1
lines changed Original file line number Diff line number Diff line change @@ -16,7 +16,7 @@ class Solution {
16
16
int n = nums.size ();
17
17
sort (nums.begin (), nums.end ());
18
18
19
- for (int i = 0 ; i < n; ++i) {
19
+ for (int i = 0 ; i < n - 2 ; ++i) {
20
20
int left = i + 1 , right = n - 1 ;
21
21
while (left < right) {
22
22
int sum = nums[i] + nums[left] + nums[right];
Original file line number Diff line number Diff line change
1
+ class Solution :
2
+ '''
3
+ Concepts: Two Pointers
4
+ 1. Sort the input array nums
5
+ 2. Make two pointers left and right at i + 1 and n - 1 respectively
6
+ 3. Check the sum of of nums[i] + nums[left] + nums[right] which is closest to the target
7
+ '''
8
+ def threeSumClosest (self , nums : List [int ], target : int ) -> int :
9
+ nums .sort ()
10
+
11
+ nLen = len (nums )
12
+ result = nums [0 ] + nums [1 ] + nums [nLen - 1 ]
13
+ for i in range (nLen - 2 ):
14
+ left = i + 1
15
+ right = nLen - 1
16
+
17
+ while left < right :
18
+ sums = nums [i ] + nums [left ] + nums [right ]
19
+ if sums == target :
20
+ return sums
21
+
22
+ if abs (sums - target ) < abs (result - target ):
23
+ result = sums
24
+
25
+ if sums > target :
26
+ right -= 1
27
+ else :
28
+ left += 1
29
+
30
+ return result
You can’t perform that action at this time.
0 commit comments