当前位置:   article > 正文

【力扣】最接近的三数之和_最接近的三数之和c语言力扣

最接近的三数之和c语言力扣

给你一个长度为 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

  1. class Solution {
  2. public int threeSumClosest(int[] nums, int target) {
  3. if(nums.length==3) return nums[0]+nums[1]+nums[2];
  4. Arrays.sort(nums);//排序
  5. int min=Integer.MAX_VALUE;//初始值为int类型的最大整数
  6. int a=0;
  7. for(int i=0;i<nums.length-1;i++) {
  8. if (i > 0 && nums[i] == nums[i - 1]) continue;//过滤重复的数
  9. int left = i+1, right = nums.length - 1;//定义双指针
  10. while (left < right) {
  11. int sum = nums[left] + nums[right] + nums[i];
  12. if (Math.abs(sum - target) < min) {//三数之和与目标值做差取绝对值,如果比min小,则替换min的值
  13. min=Math.abs(sum - target);
  14. a=sum;//存储此时的最小三数之和
  15. }
  16. if (sum == target) {
  17. return target;
  18. } else if(sum<target){
  19. left++;
  20. } else {
  21. right--;
  22. }
  23. }
  24. }
  25. return a;
  26. }
  27. public static void main(String[] args) {
  28. Solution s=new Solution();
  29. System.out.println(s.threeSumClosest(new int[]{1,1,1,0},-2));
  30. }
  31. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/寸_铁/article/detail/950263
推荐阅读
相关标签
  

闽ICP备14008679号