16. 3Sum Closest
2016-03-21 11:25
288 查看
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.
Subscribe to see which companies asked this question
做起来跟3Sum差不多的
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).
Subscribe to see which companies asked this question
做起来跟3Sum差不多的
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; } }
相关文章推荐
- MSSQL 创建用户和权限简单操作
- 解决URL传参乱码问题
- 106. Construct Binary Tree from Inorder and Postorder Traversal
- Sublime 常用插件包
- Zookeeper学习(九):ZooKeeper 实现分布式锁
- ionic 里使用 iframe 可能遇到的问题
- 百度地图-定位
- 有符号数和无符号数
- 为什么要使用SLF4J而不是Log4J
- ****如何优雅的用Axure装逼?高保真原型心得分享
- iOS_SN_CoreData数据迁移
- iOS/Android/Web Url Encode空格處理 原文連結:http://read01.com/3gDO.html
- Eclipse远程调试HDP源代码
- GDC 2016 神秘海域4中使用Substance制作Texture
- 美好的一天(Weather Live)
- 华为设计总监:年轻设计师如何进步?
- PHP计算两个经纬度之间的距离
- PHP socket实现 writeInt 和 writeLong 和 writeUTF 以及和Java端对接
- MySQL 5.6 for Windows 配置安装
- 330. Patching Array