16. 3Sum Closest
2016-03-14 16:52
639 查看
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.
在给定数列中找出三个数,使和最接近 target
还是先排序,再左右夹逼
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).
在给定数列中找出三个数,使和最接近 target
还是先排序,再左右夹逼
public class Solution { public int threeSumClosest(int[] num, int target) { Arrays.sort(num); int ret = num[0] + num[1] + num[2]; int len = num.length; for (int i = 0; i <= len - 3; i++) { // first number : num[i] int j = i + 1; // second number int k = len - 1; // third number while (j < k) { int sum = num[i] + num[j] + num[k]; if (Math.abs(sum - target) < Math.abs(ret - target)) ret = sum; if (sum < target) { ++j; } else if (sum > target) { --k; } else { ++j; --k; } } } return ret; } }
相关文章推荐
- equals和hashcode方法
- Android进阶UI之SlidingTabLayout实现ViewPager页卡滑动效果
- Android设计模式系列(7)--SDK源码之命令模式
- 括号匹配
- 进制转换
- 利用java实现的一个发送手机短信的小例子
- Android bluetooth介绍(一):基本概念及硬件接口
- 简单的线程池实现
- 关于iOS 融云的一些细节
- 双层for循环遍历数据
- Android仿IOS地区弹出框选择器
- SpringMvc form日期字符串到后台bean分秒丢失
- 最强查看依赖关系脚本
- 用宏输出0~99
- iOS 图片编辑——涂鸦——随手指移动随意画线
- Life Game-cww
- nginx的access-log中添加cookie
- First blog for IT!
- MC9S12G128 SCI设置
- [Java代码] JAVA 持有对象——容器初探(持续补充)