leetcode note--leetcode 16 3Sum Closest
来源:互联网 发布:手机淘宝上支付宝在哪 编辑:程序博客网 时间:2024/05/20 09:25
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 Solution { public int threeSumClosest(int[] nums, int target) { int len = nums.length; if(len<3)return 0; Arrays.sort(nums); int res = nums[0]+nums[1]+nums[2]; for(int i = 0;i<len-2;i++){ int left = i+1; int right = len-1; while(left<right){ int sum = nums[i]+nums[left]+nums[right]; if(sum==target)return target; res = Math.abs(sum-target)>Math.abs(res-target)?res:sum; if(sum<target)left++; else right--; } } return res; }}
time=23ms;
三个数及以上的,在找的时候,要定下一个,动另外两个,不能三个全动。。。
0 0
- leetcode note--leetcode 16 3Sum Closest
- LeetCode 16: 3Sum Closest
- LeetCode 16: 3Sum Closest
- leetcode 16 3Sum Closest
- [leetcode 16] 3Sum Closest
- Leetcode【16】:3Sum Closest
- [leetcode 16] 3Sum Closest
- [Leetcode] 16 - 3Sum Closest
- leetcode.16----------3Sum Closest
- leetcode 16 3Sum Closest
- leetcode-16 3Sum closest
- LeetCode---(16) 3 Sum Closest
- LeetCode 16 - 3Sum Closest
- leetcode 16 -- 3Sum Closest
- 3Sum Closest - LeetCode 16
- leetcode 16: 3Sum Closest
- Leetcode#16 3Sum Closest
- LeetCode(16) 3Sum Closest
- 学习笔记 vim退出
- HTTP协议与状态链接解决方案cookie,session的关系
- UML总结--类图
- Dialog 不显示
- Elasticsearch 5.0-简单查询
- leetcode note--leetcode 16 3Sum Closest
- 英语单词
- 集合、泛型集合、字典、哈希表 总结
- BZOJ3944——Sum
- JSP标准标签库(JSTL)及其标签属性
- UNIX高级环境编程(8)进程环境(Process Environment)- 进程的启动和退出、内存布局、环境变量列表
- 浅谈JavaScript引用类型——Date
- Maven3.3.9创建web项目 部署tomcat 8
- Android上实现一个简单的天气预报APP(一) 设计