|
| 1 | +# 0016. 3Sum Closest |
| 2 | + |
| 3 | +* Difficulty: medium |
| 4 | +* Link: https://leetcode.com/problems/3sum-closest/ |
| 5 | +* Topics: Array-String, Multiple-Pointers |
| 6 | + |
| 7 | +# Clarification |
| 8 | + |
| 9 | +1. Check the inputs and outputs |
| 10 | + - INPUT:List[int] |
| 11 | + - OUTPUT: integer |
| 12 | + |
| 13 | +# Naive Solution |
| 14 | + |
| 15 | +### Thought Process |
| 16 | + |
| 17 | +1. sort the array |
| 18 | +2. extend two sum |
| 19 | +3. keep the closest number |
| 20 | + 1. if equals to target : return directly |
| 21 | + 2. else: keep the closest number |
| 22 | +- Implement |
| 23 | + |
| 24 | + ```python |
| 25 | + class Solution: |
| 26 | + def threeSumClosest(self, nums: List[int], target: int) -> int: |
| 27 | + """ |
| 28 | + 1. sort the array |
| 29 | + 2. extend two sum |
| 30 | + 3. keep the closest number |
| 31 | + - if equals to target : return directly |
| 32 | + - else: keep the closest number |
| 33 | + """ |
| 34 | + nums.sort() |
| 35 | + closestSum = sys.maxsize |
| 36 | + closestDiff = abs(sys.maxsize-target) |
| 37 | + |
| 38 | + for i in range(0, len(nums) - 2): |
| 39 | + l, r = i + 1, len(nums) - 1 |
| 40 | + while l < r: |
| 41 | + s = nums[i] + nums[l] + nums[r] |
| 42 | + diff = s - target |
| 43 | + if abs(diff) < closestDiff: |
| 44 | + closestDiff = abs(diff) |
| 45 | + closest = s |
| 46 | + if diff > 0: |
| 47 | + r -= 1 |
| 48 | + elif diff < 0: |
| 49 | + l += 1 |
| 50 | + else: |
| 51 | + return target |
| 52 | + |
| 53 | + return closest |
| 54 | + ``` |
| 55 | + |
| 56 | + |
| 57 | +### Complexity |
| 58 | + |
| 59 | +- Time complexity:$O(n^2)$ |
| 60 | +- Space complexity:$O(1)$ |
| 61 | + |
| 62 | +### Problems & Improvement |
| 63 | + |
| 64 | +- 不需要額外存 closestDiff |
| 65 | + |
| 66 | +# Improvement |
| 67 | + |
| 68 | +### Thought Process |
| 69 | + |
| 70 | +- Implement |
| 71 | + |
| 72 | + ```python |
| 73 | + class Solution: |
| 74 | + def threeSumClosest(self, nums: List[int], target: int) -> int: |
| 75 | + """ |
| 76 | + 1. sort the array |
| 77 | + 2. extend two sum |
| 78 | + 3. keep the closest number |
| 79 | + - if equals to target : return directly |
| 80 | + - else: keep the closest number |
| 81 | + """ |
| 82 | + nums.sort() |
| 83 | + closest = nums[0] + nums[1] + nums[2] |
| 84 | + |
| 85 | + for i in range(0, len(nums) - 2): |
| 86 | + l, r = i + 1, len(nums) - 1 |
| 87 | + while l < r: |
| 88 | + s = nums[i] + nums[l] + nums[r] |
| 89 | + diff = s - target |
| 90 | + if abs(s - target) < abs(closest - target): |
| 91 | + closest = s |
| 92 | + if s > target: |
| 93 | + r -= 1 |
| 94 | + elif s < target: |
| 95 | + l += 1 |
| 96 | + else: |
| 97 | + return target |
| 98 | + |
| 99 | + return closest |
| 100 | + ``` |
0 commit comments