We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
2 parents 6fa9e51 + 6a8f3ce commit 50e054aCopy full SHA for 50e054a
2 files changed
LeetCode/medium/three_sum_closest_16.py
@@ -0,0 +1,20 @@
1
+from typing import List
2
+
3
4
+class Solution:
5
+ def threeSumClosest(self, nums: List[int], target: int) -> int:
6
+ nums.sort()
7
+ closest = nums[0] + nums[1] + nums[2]
8
9
+ for index in range(len(nums)):
10
+ left, right = index + 1, len(nums) - 1
11
12
+ while left < right:
13
+ three_sum = nums[index] + nums[left] + nums[right]
14
+ if three_sum < target:
15
+ left += 1
16
+ else:
17
+ right -= 1
18
+ if abs(three_sum - target) < abs(closest - target):
19
+ closest = three_sum
20
+ return closest
tests/test_leetcode_medium.py
@@ -155,6 +155,25 @@ def test_three_sum(nums, expected):
155
assert normalized_result == normalized_expected
156
157
158
+@pytest.mark.parametrize(
159
+ "nums, target, expected",
160
+ [
161
+ ([-1, 2, 1, -4], 1, 2),
162
+ ([0, 0, 0], 1, 0),
163
+ ([0, 0, 0], 0, 0),
164
+ ([1, 1, 1, 0], -100, 2),
165
+ ([1, 1, -1, -1, 3], -1, -1),
166
+ ([-3, -2, -5, 3, -4], -1, -2),
167
+ ([4, 0, 5, -5, 3, 3, 0, -4, -5], -2, -2),
168
+ ],
169
+)
170
+def test_three_sum_closest(nums, target, expected):
171
+ from LeetCode.medium.three_sum_closest_16 import Solution
172
173
+ result = Solution().threeSumClosest(nums, target)
174
+ assert result == expected, f"expected: {expected} but got: {result}"
175
176
177
# 05: Longest Palindromic Substring
178
# https://leetcode.com/problems/longest-palindromic-substring/?envType=problem-list-v2&envId=hash-table
179
0 commit comments