LeetCode 16 3Sum Closest
2015-08-05 22:35
375 查看
3Sum Closest
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 haveexactly 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).
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.
解题思路: 这道题的基本实现方法与3-sum一致,而且更为简单。只要找到最接近target那个数即可。实现方法为,记录每次的求和的结果,返回最小值。我一开始很天真的把3-sum的实现拿过来随便修改一下就提交了,结果狠狠地打了我的脸,因为3-sum中重复性判断的语句并不适用于3-sum
closest。因为两者的边界条件并不一致,只有当出现完全等于target的时候,才会出现重复性判断,而closest找到一个接近值的时候就已经触发重复性判断,这样会导致错过那个更接近的值。因此,在消除重复性逻辑判断以后,符合题目要求。
比如 {20 -19 -19 -18 -18} -59,若按照原来的重复性判断,结果会是-57,而实质上的最接近值为-58,因为当指针指向-19的时候由于重复性判断,start和end都指向同一个-19这时start已经==end了,跳出循环,错过最接近值。因此,需要消除重复性判断。
代码如下:public int threeSumClosest(int[] nums, int target) { Arrays.sort(nums); int len =nums.length; int min =Integer.MAX_VALUE;//记录最小的re int d =Integer.MAX_VALUE;//记录当前最小的差值 for (int i = 0; i < len-2; i++) {//len-2已经包含所有情况 if(i>0&&nums[i]==nums[i-1])continue;//这里是i-1与i的判断因为for循环i++了 int start =i+1; int end = len-1; int s = nums[i]; while(start<end){ int re = s +nums[start]+nums[end]; int t = Math.abs(re - target); if(t<=d){ min = re; d = t; } if(re>target){ end--; //while (start < end && nums[end] == nums[end-1]) end--; //消除的重复性判断 }else if(re<target){ start++; // while (start < end && nums[start] == nums[start+1]) start++; //消除的重复性判断 }else{ return min; } } } return min; }
相关文章推荐
- iOS 8 AutoLayout与Size Class自悟
- CMD 使用emulator.exe启动Android模拟器——emulator -data 镜像文件名称
- Ubuntu 和 Redhat / Fedora 服务管理命令对比表(附Fedora16新的服务管理工具systemctl )
- Android - Fragment (三)不同Fragment之间的通信
- js中ajax的异步性
- (一〇八)iPad开发之横竖屏适配
- linux 使用共享内存
- [经典技巧]android 如何监听输入法是否弹出或隐藏,监听手机是否是全屏切换
- (一〇八)iPad开发之横竖屏适配
- 多行文本溢出显示省略号(…) text-overflow: ellipsis
- Scala 深入浅出实战经典 第49课 Scala中Variance代码实战(协变)
- 乙未年六月廿一 学习笔记
- 树莓派实战2:发送ip地址到自己邮箱
- CodeForces 46D Parking Pot(线段树区间更新)
- ios8 UITableView设置 setSeparatorInset:UIEdgeInsetsZero不起作用的解决办法
- WPF和Windows Phone Post组装函数
- rewrite(摘自Yii2)
- swift学习1 oc swift混编
- 增加eclipse的内存
- ubuntu服务管理