leetcode 016: 最接近的三数之和
给你一个长度为 n
的整数数组 nums
和 一个目标值 target
。请你从 nums
中选出三个整数,使它们的和与 target
最接近。
返回这三个数的和。
假定每组输入只存在恰好一个解。
示例 1:
输入:nums = [-1,2,1,-4], target = 1 输出:2 解释:与 target 最接近的和是 2 (-1 + 2 + 1 = 2) 。
示例 2:
输入:nums = [0,0,0], target = 1 输出:0
提示:
-
3 <= nums.length <= 1000
-
-1000 <= nums[i] <= 1000
-
-104 <= target <= 104
Related Topics
数组
双指针
排序
思路1 : 暴力破解法
把每种情况都枚举到。时间性能很差。
思路2: 排序 + 双指针
思路参考三数之和
注意: 当枚举a时,如果一个值重复,那么就不需要计算。这一点性能相差很大。可以参考以下代码比较。
public int threeSumClosest(int[] nums, int target) { Arrays.sort(nums); int result = nums[0]+nums[1]+nums[2]; //枚举a for(int first = 0 ; first < nums.length-2 ; first++){ /** if(first > 0 && nums[first] == nums[first-1]){ continue; }*/ //当 a + b + c >target时,我们需要将c向左移动 //当a + b +c < target时 我们需要将b向右移动 最终可以确定一个最接近的结果 int second = first + 1; int third = nums.length - 1; int count; while(second<third){ //保证b唯一 if(second > first + 1 && nums[second] == nums[second-1]){ second++; continue; } //计算和 并判断出最接近的数 count = nums[first] + nums[second] + nums[third]; result = Math.abs(count-target) > Math.abs(result - target) ? result : count; if(count > target){ third--; }else if(count < target){ second++; }else{//target == count return count; } } //找到最接近的那个数 和之前的进行比较 } return result; } 解答成功: 执行耗时:7 ms,击败了28.53% 的Java用户 内存消耗:38.2 MB,击败了14.28% 的Java用户 ----------------------------------------------------------------------------------------------------- public int threeSumClosest(int[] nums, int target) { Arrays.sort(nums); int result = nums[0]+nums[1]+nums[2]; //枚举a for(int first = 0 ; first < nums.length-2 ; first++){ if(first > 0 && nums[first] == nums[first-1]){ continue; } //当 a + b + c >target时,我们需要将c向左移动 //当a + b +c < target时 我们需要将b向右移动 最终可以确定一个最接近的结果 int second = first + 1; int third = nums.length - 1; int count; while(second<third){ //保证b唯一 if(second > first + 1 && nums[second] == nums[second-1]){ second++; continue; } //计算和 并判断出最接近的数 count = nums[first] + nums[second] + nums[third]; result = Math.abs(count-target) > Math.abs(result - target) ? result : count; if(count > target){ third--; }else if(count < target){ second++; }else{//target == count return count; } } //找到最接近的那个数 和之前的进行比较 } return result; } 解答成功: 执行耗时:4 ms,击败了97.19% 的Java用户 内存消耗:38.3 MB,击败了6.03% 的Java用户