16. 3Sum Closest
https://leetcode.com/problems/3sum-closest/
Given an array nums
of n integers 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:
Constraints:
3 <= nums.length <= 10^3
-10^3 <= nums[i] <= 10^3
-10^4 <= target <= 10^4
Thoughts
数组中找三元组,它的和与target最近的。暴力法O(N^3)=>往O(N^2)优化。排序后nums[i]作为最大元素的候选,在i元素前找和最接近target-nums[i]的二元对,2sum。2sum用首尾双指针。
Code
Analysis
Errors:
不需要考虑目标(res)应是sum-target还是target-sum,因为算法都是尽量向target靠。
TC:
Last updated
Was this helpful?