[LeetCode] 16. 3Sum Closest
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
-104 <= target <= 104
最接近的三数之和。
给你一个长度为 n 的整数数组 nums 和 一个目标值 target。请你从 nums 中选出三个整数,使它们的和与 target 最接近。
返回这三个数的和。
假定每组输入只存在恰好一个解。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/3sum-closest
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题意是给一个数组和一个 target 数字,返回一个三数之和使得 nums[A] + nums[B] + nums[C] = target 或尽可能接近 target。
思路跟15题类似,也是需要先排序。排序之后,先固定第一个数字,然后后两个数字之间做 two pointer 逼近。逼近的方式是如果
- res = nums[A] + nums[B] + nums[C] = target,则直接返回这个res;
- 如果res大于target,C--
- 如果res小于target,B++
注意在排序过后, res 的初始化是 res = nums[0] + nums[1] + nums[nums.length - 1]。因为这个值是全局最小的三数之和。
时间O(n^2)
空间O(1)
JavaScript实现
1 /** 2 * @param {number[]} nums 3 * @param {number} target 4 * @return {number} 5 */ 6 var threeSumClosest = function(nums, target) { 7 nums = nums.sort((a, b) => a - b); 8 const len = nums.length; 9 let res = nums[0] + nums[1] + nums[len - 1]; 10 let low, high, sum; 11 for (let i = 0; i < nums.length - 2; i++) { 12 low = i + 1; 13 high = nums.length - 1; 14 while (low < high) { 15 sum = nums[i] + nums[low] + nums[high]; 16 if (Math.abs(target - sum) < Math.abs(target - res)) { 17 res = sum; 18 } 19 if (sum > target) { 20 high--; 21 } else { 22 low++; 23 } 24 } 25 } 26 return res; 27 };
Java实现
1 class Solution { 2 public int threeSumClosest(int[] nums, int target) { 3 int res = nums[0] + nums[1] + nums[nums.length - 1]; 4 Arrays.sort(nums); 5 6 for (int i = 0; i < nums.length - 2; i++) { 7 int start = i + 1; 8 int end = nums.length - 1; 9 while (start < end) { 10 int sum = nums[i] + nums[start] + nums[end]; 11 if (sum > target) { 12 end--; 13 } else { 14 start++; 15 } 16 if (Math.abs(target - sum) < Math.abs(target - res)) { 17 res = sum; 18 } 19 } 20 } 21 return res; 22 } 23 }