59.3Sum Closest-最接近的三数之和(中等题)
来源:互联网 发布:手机赚钱软件 编辑:程序博客网 时间:2024/04/29 20:49
,##
题目
给一个包含 n 个整数的数组 S, 找到和与给定整数 target 最接近的三元组,返回这三个数的和。
注意事项
只需要返回三元组之和,无需返回三元组本身样例
例如 S = [-1, 2, 1, -4] and target = 1. 和最接近 1 的三元组是 -1 + 2 + 1 = 2.
挑战
O(n^2) 时间, O(1) 额外空间。
题解
排序后遍历,取最接近target的三个元素之和,可参见57.3Sum-三数之和(中等题)
public class Solution { /** * @param numbers: Give an array numbers of n integer * @param target : An integer * @return : return the sum of the three integers, the sum closest target. */ public int threeSumClosest(int[] numbers ,int target) { int n = numbers.length; Arrays.sort(numbers); int closet = Integer.MAX_VALUE/2; for (int i = 0; i < numbers.length - 2; i++) { int left = i + 1; int right = numbers.length - 1; while (left < right) { int sum = numbers[i] + numbers[left] + numbers[right]; if (sum == target) { return sum; } else if (sum < target) { left++; } else { right--; } closet = Math.abs(sum-target) < Math.abs(closet-target)?sum:closet; } } return closet; }}
Last Update 2016.9.30
0 0
- 59.3Sum Closest-最接近的三数之和(中等题)
- 57.3Sum-三数之和(中等题)
- 139.Subarray Sum Closest-最接近零的子数组和(中等题)
- 3Sum Closest 三数最接近
- 最接近的三数之和
- 最接近的三数之和
- [LeetCode]—3Sum Closest 求数组中三个数之和最接近给定target的组合
- 3Sum Closest(离目标值最近的三数之和)
- [LeetCode] 3Sum Closest 最近的三数之和 Python
- 56.Two Sum-两数之和(中等题)
- 58.4Sum-四数之和(中等题)
- LeetCode OJ-16.3Sum Closest(最接近三数和)
- LintCode:最接近的三数之和
- LintCode 52-最接近的三数之和
- LintCode 59 最接近的三数之和
- 最接近的三数之和 _LintCode
- 【lintcode】两数之和、三数之和、最接近的三数之和、四数之和小结
- 3Sum Closest 三个数的和最接近某个值
- gluPerspective 的聚焦点/zNear/zFar
- Codeforces372 E. Digit Tree 树分治
- 网络爬虫学习笔记(二) 如何开发一个简单的爬虫
- 洛谷 P1122 最大子树和
- MVC框架
- 59.3Sum Closest-最接近的三数之和(中等题)
- Eighty seven (bitset优化) 在n个数中取m个数和为k
- Socket(Tcp)传输在流前面加标识
- 只要情结,不管实用的loT集锦
- 如何用Qt打开Android图像库
- WPF 高质量教程(转载自圣殿骑士)
- JAVA子类对象访问父类被重写方法
- Unity3d-XML将一个”非”xml的字符串变成规范的xml格式
- web前端-CSS Backgrounds-004