问题:

Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target.
Return the sum of the three integers. You may assume that each input would have exactly one solution.
For example, given array S = {-1 2 1 -4}, and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

官方难度:

Medium

翻译:

给定一个长度为n的无序数组S,找出其中的3个整数,使这3个整数的和最接近于一个给定的目标值,返回这3个整数的和。

假定整个数组中的解是唯一的。

例子:

数组S:{ -1,2,1,-4},目标值target=1。

解为2(-1+2+1=2)。

  1. 这题的解法,与No.015(3Sum)的解法基本相同,先排序,然后通过外循环遍历+内循环夹逼的方法实现。
  2. 与3Sum问题不同的是,除了维护上一个值是否与当前值相同,其余的优化方法都不能使用。另外,previous的初始值,不能影响第一次计算。
  3. 维护一个差值closest,这个值要保证是正数。由于解唯一确定,所以在循环过程中,如果出现closest=0的情况,可以直接返回。注意返回值不是差值,而是三个数值的和。
  4. 注意入参检查。

解题代码:

 // 返回值是数组3个元素的和,不是差值
public static int threeSumClosest(int[] nums, int target) {
if (nums == null || nums.length < 3) {
throw new IllegalArgumentException("Input error");
}
Arrays.sort(nums);
// 初始差值和返回值
int returnNo = Integer.MAX_VALUE;
int closest = Integer.MAX_VALUE;
int previous = Integer.MAX_VALUE;
for (int i = 0; i < nums.length - 2; i++) {
if (nums[i] == previous) {
continue;
}else{
previous = nums[i];
}
// 数组剩余部分夹逼
int left = i + 1;
int right = nums.length - 1;
// 转化为2Sum Closest问题
int remainTarget = target - nums[i];
int sum;
int preLeft = Integer.MIN_VALUE, preRight = Integer.MIN_VALUE;
while (left < right) {
if (nums[left] == preLeft) {
left++;
continue;
}
if (nums[right] == preRight) {
right--;
continue;
}
sum = nums[left] + nums[right];
// 解唯一确定,直接返回
if (remainTarget - sum == 0) {
return sum + nums[i];
}
// 最小值替换,返回值赋值
int temp = Math.abs(remainTarget - sum);
if (temp < closest) {
returnNo = nums[i] + nums[left] + nums[right];
closest = temp;
}
if (remainTarget - sum > 0) {
left++;
} else {
right--;
}
}
}
return returnNo;
}

threeSumClosest

相关链接:

https://leetcode.com/problems/3sum-closest/

https://github.com/Gerrard-Feng/LeetCode/blob/master/LeetCode/src/com/gerrard/algorithm/medium/Q016.java

PS:如有不正确或提高效率的方法,欢迎留言,谢谢!

No.016:3Sum Closest的更多相关文章

  1. LeetCode第[16]题(Java):3Sum Closest 标签:Array

    题目难度:Medium 题目: Given an array S of n integers, find three integers in S such that the sum is closes ...

  2. LeetCode第[16]题(Java):3Sum Closest (和目标值最接近的三个数的和)——Medium

    题目难度:Medium 题目: Given an array S of n integers, find three integers in S such that the sum is closes ...

  3. LeetCode OJ:3Sum Closest(最接近的三数之和)

    Given an array S of n integers, find three integers in S such that the sum is closest to a given num ...

  4. leetcode笔记:3Sum Closest

    一.题目描写叙述 二.解题技巧 该题与3Sum的要求类似.不同的是要求选出的组合的和与目标值target最接近而不一定相等.但实际上,与3Sum的算法流程思路类似,先是进行排序.然后顺序选择数组A中的 ...

  5. 【LeetCode OJ 016】3Sum Closest

    题目链接:https://leetcode.com/problems/3sum-closest/ 题目:Given an array S of n integers, find three integ ...

  6. No.016 3Sum Closest

    16. 3Sum Closest Total Accepted: 86565 Total Submissions: 291260 Difficulty: Medium Given an array S ...

  7. LeetCode之“散列表”:Two Sum && 3Sum && 3Sum Closest && 4Sum

    1. Two Sum 题目链接 题目要求: Given an array of integers, find two numbers such that they add up to a specif ...

  8. LeetCode--No.016 3Sum Closest

    16. 3Sum Closest Total Accepted: 86565 Total Submissions: 291260 Difficulty: Medium Given an array S ...

  9. [LeetCode] 3Sum Closest 最近三数之和

    Given an array S of n integers, find three integers in S such that the sum is closest to a given num ...

随机推荐

  1. [Java面试十一]数据库总结.

    问题及描述: --1.学生表 Student(SID,Sname,Sage,Ssex) --SID 学生编号,Sname 学生姓名,Sage 出生年月,Ssex 学生性别 --2.课程表 Course ...

  2. Atitit 基于dom的游戏引擎

    Atitit 基于dom的游戏引擎 1. 添加sprite控件(cocos,createjs,dom)1 1.1.1. Cocos1 1.1.2. createjs1 1.1.3. Dom模式2 1. ...

  3. node.js 简介

    简介:     Node,是一个可以让 JavaScript 运行在服务器端的平台.它可以让 JavaScript 脱离浏览器的束缚运行在一般的服务器环境下     Node.js 是一个为实时Web ...

  4. Java EE开发平台随手记3——Mybatis扩展2

    忙里偷闲,继续上周的话题,记录Mybatis的扩展. 扩展5:设置默认的返回结果类型 大家知道,在Mybatis的sql-mapper配置文件中,我们需要给<select>元素添加resu ...

  5. Java 线程 — AbstractQueuedSynchronizer

    锁 锁就是一种状态,比如互斥锁:同一时间只能有一个线程拥有,可以使用一个整型值来标志当前的状态 0:表示没有现成占有锁 1:表示锁已经被占用 AbstractQueuedSynchronizer 实现 ...

  6. 快速入门系列--MVC--06视图

    到了View的呈现板块,感觉ASP.NET MVC的学习也进入了尾声,还是比较开心的,毕竟也有了不小收获.这部分内容相对比较简单,因为之前还专门学习过如何结合HTML5与MVC框架.前文中提到过,Ac ...

  7. SQL Server中的版本号

        在SQL Server中,通常版本号的命名是大版本.小版本.累积更新这种形式,比如说9.X.XXX就是SQL Server 2005.下面我将把SQL Server中版本号对应的版本列出来,以 ...

  8. knockoutjs中使用mapping插件绑定数据列表

    使用KO绑定数据列表示例:   1.先申请V,T,T2三个辅助方法,方便调试.声明viewModel和加载数据时的映射条件mapping    2.先使用ko.mapping.fromJS()将原来的 ...

  9. IIS 6中mimemap属性的默认设置

    Collapse this tableExpand this table Extension MIME type .ra audio/x-pn-realaudio .sv4crc applicatio ...

  10. PHP Log时时查看小工具

    以前Log都是打印在一个文档中,然后打开文件夹,最后打开文档查看里面的内容,每次打开文件夹感觉很烦. 前些日子看到同事开发.NET的时候,用他自己的一个小工具能够时时查看到Log的内容,非常方便,所以 ...