KK's blog

每天积累多一些

0%

LeetCode 016 3Sum Closest

LeetCode



Given an integer array nums of length n and an integer target, find three integers in nums such that the sum is closest to target.

Return the sum of the three integers.

You may assume that each input would have exactly one solution.

Example 1:

Input: nums = [-1,2,1,-4], target = 1
Output: 2
Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).


Example 2:

Input: nums = [0,0,0], target = 1
Output: 0


Constraints:

3 <= nums.length <= 1000 -1000 <= nums[i] <= 1000
* -10<sup>4</sup> <= target <= 10<sup>4</sup>

题目大意:

三数和最接近target

解题思路:

N/A

解题步骤:

N/A

注意事项:

  1. 此题不需去重,若等于target可直接返回

Python代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def threeSumClosest(self, nums: List[int], target: int) -> int:
nums.sort()
res = float('inf')
for i in range(len(nums)):
left, right = i + 1, len(nums) - 1
while left < right:
temp = nums[i] + nums[left] + nums[right]
if abs(temp - target) < abs(res - target):
res = temp
if temp < target:
left += 1
elif temp > target:
right -= 1
else:
return target
return res

算法分析:

时间复杂度为O(n2),空间复杂度O(1)

Free mock interview