赞
踩
给你一个长度为 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
易错示例:
输入:nums=[833,736,953,-584,-448,207,128,-445,126,248,871,860,333,-899,463,488,-50,-331,903,575,265,162,-733,648,678,549,579,-172,-897,562,-503,-508,858,259,-347,-162,-505,-694,300,-40,-147,383,-221,-28,-699,36,-229,960,317,-585,879,406,2,409,-393,-934,67,71,-312,787,161,514,865,60,555,843,-725,-966,-352,862,821,803,-835,-635,476,-704,-78,393,212,767,-833,543,923,-993,274,-839,389,447,741,999,-87,599,-349,-515,-553,-14,-421,-294,-204,-713,497,168,337,-345,-948,145,625,901,34,-306,-546,-536,332,-467,-729,229,-170,-915,407,450,159,-385,163,-420,58,869,308,-494,367,-33,205,-823,-869,478,-238,-375,352,113,-741,-970,-990,802,-173,-977,464,-801,-408,-77,694,-58,-796,-599,-918,643,-651,-555,864,-274,534,211,-910,815,-102,24,-461,-146],
target=-7111输出:-2960
提示:
3 <= nums.length <= 1000
-1000 <= nums[i] <= 1000
-104 <= target <= 104
- class Solution {
- public int threeSumClosest(int[] nums, int target) {
- if(nums.length==3) return nums[0]+nums[1]+nums[2];
- Arrays.sort(nums);//排序
- int min=Integer.MAX_VALUE;//初始值为int类型的最大整数
- int a=0;
- for(int i=0;i<nums.length-1;i++) {
- if (i > 0 && nums[i] == nums[i - 1]) continue;//过滤重复的数
- int left = i+1, right = nums.length - 1;//定义双指针
- while (left < right) {
- int sum = nums[left] + nums[right] + nums[i];
- if (Math.abs(sum - target) < min) {//三数之和与目标值做差取绝对值,如果比min小,则替换min的值
- min=Math.abs(sum - target);
- a=sum;//存储此时的最小三数之和
- }
- if (sum == target) {
- return target;
- } else if(sum<target){
- left++;
- } else {
- right--;
- }
- }
- }
- return a;
- }
- public static void main(String[] args) {
- Solution s=new Solution();
- System.out.println(s.threeSumClosest(new int[]{1,1,1,0},-2));
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。