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
注意事项:
- 此题不需去重,若等于target可直接返回
Python代码:
1 | def threeSumClosest(self, nums: List[int], target: int) -> int: |
算法分析:
时间复杂度为O(n2)
,空间复杂度O(1)