16.3Sum Closest
来源:互联网 发布:二分查找算法举例说明 编辑:程序博客网 时间:2024/06/10 11:48
题目描述
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.
Example:
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).
思路分析
这题和求三个数之和为定值的思路相似。不同之处在与求最接近target的三个数。排序后,我们可以先设定ans = nums[0]+nums[1]+nums[2],然后依次遍历,对于任意组合的三个数值,他们的和sum和target差的绝对值与ans与target差的绝对值相比较,不断更新ans,使得其保持最小值。
代码
public int threeSumClosest(int[] nums, int target) { Arrays.sort(nums); int ans = nums[0]+nums[1]+nums[2]; int len = nums.length; int sum = 0; for (int i = 0; i < len-2; i++) { int j = i+1,k = len-1; while(j<k) { sum = nums[i]+nums[j]+nums[k]; if(Math.abs(sum-target)<Math.abs(ans-target)) { ans = sum; } if(sum>target) k--; else j++; } } return ans; }
阅读全文
0 0
- 15.3Sum &16.3Sum Closest
- [LeetCode]16.3Sum Closest
- LeetCode 16.3Sum Closest
- 16.3Sum Closest
- 16.3Sum Closest
- [leetcode] 16.3Sum Closest
- LeetCode-16.3Sum Closest
- Leetcode||16.3Sum Closest
- LeetCode 16.3Sum Closest
- 16.3Sum Closest
- LeetCode----- 16.3Sum Closest
- 16.3Sum Closest
- Algorithms—16.3Sum Closest
- [leetcode]16.3Sum Closest(Java实现)
- 【leetcode】16.3Sum Closest 方法总结
- leetcode 1|167.two sum 1|2 && 3.three sum && 16.3Sum Closest && 18. 4Sum
- 3 Sum & 3 Sum Closest
- 【Leetcode】3Sum Closest (Sum)
- 使用hangout-output-clickhouse将数据实时清洗写入ClickHouse
- Java 代码性能优化总结
- 51Nod
- 重大改革!教育部将Python纳入全国计算机等级考试科目
- 理解 Vue.js中的v-for功能
- 16.3Sum Closest
- MySQL的两个命令 ---- explain和procedure analyse
- 永远不要通过贬低他人而获得优越感
- form 表单序列号
- libEasyPlayer RTSP windows播放器SDK API接口设计说明
- Python基本操作
- 微程序控制器之微程序控制的工作过程
- IDEA 编译MAVEN项目
- [leetcode]125. Valid Palindrome[facebook]