leetcode16~3Sum Closest
来源:互联网 发布:远程会诊软件 编辑:程序博客网 时间:2024/06/06 07:18
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).
与上题类似,只需要添加一个变量记录最小差值,然后更新结果值即可。
public class ThreeSumClosest { public int threeSumClosest(int[] nums, int target) { if(nums==null || nums.length<3) return 0; //先排序 Arrays.sort(nums); int closest = Integer.MAX_VALUE; int res = 0; for(int i=0;i<nums.length-2;i++) { if(i>1 && nums[i]==nums[i-1]) continue; //固定nums[i] int top = i+1,tail=nums.length-1; while(top<tail) { int sum = nums[i]+nums[top]+nums[tail]; if(sum<target) { if(target-sum<closest) { //更新最小的差值 closest = target-sum; res = sum; } top++; } else if(sum>target) { if(sum-target<closest) { closest = sum-target; res = sum; } tail--; } else { //相等,则直接返回 return sum; } } } return res; }}
0 0
- [LeetCode16]3Sum Closest
- LeetCode16:3Sum Closest
- leetcode16 3Sum Closest
- LeetCode16:3Sum Closest
- LeetCode16. 3Sum Closest
- leetcode16:3Sum Closest
- Leetcode16. 3Sum Closest
- leetcode16~3Sum Closest
- LeetCode16. 3Sum Closest
- leetcode16. 3Sum Closest
- leetcode16. 3Sum Closest
- leetcode16. 3Sum Closest
- LeetCode16 3Sum Closest
- LeetCode16——3Sum Closest
- leetcode16 3Sum Closest(java实现)
- [LeetCode16]3Sum Closed
- 3 Sum & 3 Sum Closest
- 【Leetcode】3Sum Closest (Sum)
- libevent源码深度剖析一
- input或textarea框动态限制字数
- Struts中实体类的字段名称要对应jsp中textfield中name属性值
- Java使用Redis实现分布式锁
- Sublime text 2/3 中 Package Control 的安装与使用方法
- leetcode16~3Sum Closest
- Android recovery分析(一)---全量升级包的编译流程
- Nginx优化
- 人机界面设计
- libevent源码深度剖析二
- 关于Div半透明子元素不透明的问题
- 继上次总结了点html标签,现在再写一些
- 刽子手游戏
- C#调用C++编写的DLL函数, 以及各种类型的参数传递 (转载)