Skip to content

Commit a7e90d7

Browse files
committed
D. J.:
- Added the leetcode problem and solution for 16
1 parent 1c388b3 commit a7e90d7

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
"""Base class for all LeetCode Problems."""
6+
7+
def threeSumClosest(self, nums: List[int], target: int) -> int:
8+
"""
9+
Given an integer array nums of length n and an integer target, find three
10+
integers in nums such that the sum is closest to target.
11+
12+
Return the sum of the three integers.
13+
14+
You may assume that each input would have exactly one solution.
15+
"""
16+
# Time Complexity: O(n^2)
17+
# Space Complexity: O(1)
18+
nums = sorted(nums)
19+
closestSum = -float("inf")
20+
i = 0
21+
while i < len(nums) - 2:
22+
if i > 0 and nums[i] == nums[i - 1]:
23+
i += 1
24+
continue
25+
left, right = i + 1, len(nums) - 1
26+
while left < right:
27+
threeSum = nums[i] + nums[left] + nums[right]
28+
if abs(target - threeSum) < abs(target - closestSum):
29+
closestSum = threeSum
30+
if threeSum > target:
31+
right -= 1
32+
elif threeSum < target:
33+
left += 1
34+
else:
35+
left += 1
36+
while left < right and nums[left] == nums[left - 1]:
37+
left += 1
38+
i += 1
39+
return closestSum

tests/test_16_3sum_closest.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
from typing import List
2+
3+
import pytest
4+
5+
from awesome_python_leetcode._16_3sum_closest import Solution
6+
7+
8+
@pytest.mark.parametrize(
9+
argnames=["nums", "target", "expected"],
10+
argvalues=[
11+
([-1, 2, 1, -4], 1, 2),
12+
([0, 0, 0], 1, 0),
13+
],
14+
)
15+
def test_func(nums: List[int], target: int, expected: int):
16+
"""Tests the solution of a LeetCode problem."""
17+
closest = Solution().threeSumClosest(nums, target)
18+
assert closest == expected

0 commit comments

Comments
 (0)