Skip to content

Commit e726d46

Browse files
committed
LC-16 Python accepted
1 parent b0afdc0 commit e726d46

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

LC-16/LC-16.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ class Solution {
1616
int n = nums.size();
1717
sort(nums.begin(), nums.end());
1818

19-
for (int i = 0; i < n; ++i) {
19+
for (int i = 0; i < n - 2; ++i) {
2020
int left = i + 1, right = n - 1;
2121
while (left < right) {
2222
int sum = nums[i] + nums[left] + nums[right];

LC-16/LC-16.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
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

0 commit comments

Comments
 (0)