16. 3Sum Closest
来源:互联网 发布:mac地址表老化时间 编辑:程序博客网 时间:2024/05/18 02:08
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).
java
class Solution { public int threeSumClosest(int[] nums, int target) { if (nums == null || nums.length < 3) { return 0; } Arrays.sort(nums); int diff = 0; int ref = Integer.MAX_VALUE; for (int i = 0; i < nums.length - 2; i++) { int temp = util(nums, i + 1, nums[i], target); if (ref > Math.abs(temp - target)) { ref = Math.abs(temp - target); diff = temp; } } return diff; } private int util(int[] nums, int start, int val, int target) { int left = start; int right = nums.length - 1; int diff = 0; int ref = Integer.MAX_VALUE; int value = 0; while (left < right) { value = val + nums[left] + nums[right]; if (left < right && value < target) { left++; if (ref > Math.abs(value - target)) { ref = Math.abs(value - target); diff = value; } } if (left < right && value > target) { right--; if (ref > Math.abs(value - target)) { ref = Math.abs(value - target); diff = value; } } if (left < right && value == target) { diff = value; break; } } return diff; }}
阅读全文
0 0
- 16. 3Sum Closest
- 16. 3Sum Closest
- 16. 3Sum Closest
- 16. 3Sum Closest
- 16. 3Sum Closest
- 16. 3Sum Closest
- 16. 3Sum Closest
- 16. 3Sum Closest
- 16. 3Sum Closest
- 16. 3Sum Closest
- 16. 3Sum Closest
- 16. 3Sum Closest
- 16. 3Sum Closest
- 16. 3Sum Closest
- 16. 3Sum Closest
- 16. 3Sum Closest
- 16. 3Sum Closest
- 16. 3Sum Closest
- 反射和正则基础
- 简单理解委托和事件
- IO(输入输出)(一)字节流
- QT 对于按钮实现的思考
- CentOS7使用YUM安装Adobe Flash Player
- 16. 3Sum Closest
- 模拟
- 2017
- Linux 安装redis以及redis扩展
- 初识线程1---入门1
- Linux 文件目录 ls 文件类型
- 回文树
- 关于xlwt模块中 write(r,c)方法中的 R与C
- 生活小记30