15. 3Sum 과 유사
class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
nums.sort()
n = len(nums)
diff = float('inf')
res = 0
for i in range(n - 2):
left = i + 1
right = n - 1
while left < right:
s = nums[left] + nums[right] + nums[i]
if abs(target - s) < diff:
diff = abs(target - s)
res = s
if s < target:
left += 1
else:
right -= 1
return res
'CS > 알고리즘' 카테고리의 다른 글
[Leetcode] 34. Find First and Last Position of Element in Sorted Array (0) | 2023.05.01 |
---|---|
[Leetcode] 17. Letter Combinations of a Phone Number (0) | 2023.05.01 |
[Leetcode] 15. 3Sum (0) | 2023.05.01 |
[Leetcode] 1. Two Sum (0) | 2023.05.01 |
[Leetcode] 12. Integer to Roman (0) | 2023.05.01 |