LeetCode 16 最接近的三数之和
2019-03-27 22:43
423 查看
给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。
例如,给定数组 nums = [-1,2,1,-4] 和 target = 1.
与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2).
这道题比前一题(三数之和)简单许多,只需要先排序,后遍历一遍就可以了,同样使用双指针。
c++代码
class Solution { public: int threeSumClosest(vector<int>& nums, int target) { sort(nums.begin(), nums.end()); int res = nums[0] + nums[1] + nums[2]; for(int i = 0; i < nums.size() - 2; i++) { int j = i + 1, k = nums.size() - 1; while(j < k) { int temp = nums[i] + nums[j] + nums[k]; if(abs(res-target) > abs(temp-target)) res = temp; if(temp == target) return target; //如果相等肯定是最接近的 else if(temp > target) k--; else j++; } } return res; } };
相关文章推荐
- leetcode16---最接近的三数之和
- LeetCode16.最接近的三数之和
- Leetcode刷题38-16.最接近的三数之和(C++)
- LeetCode- 16. 最接近的三数之和 (Medium)python和c++实现
- LeetCode 16. 最接近的三数之和
- 【PHP解法==LeetCode查找类型问题2(N数之和)】15.三数之和 && 16.最接近的三数之和 && 18.四数之和 && 454.四数相加II
- 16. 最接近的三数之和(leetcode Java语言)
- leetcode 16. 最接近的三数之和(Java版)
- LeetCode题解(python)-16. 最接近的三数之和
- leetcode 16 最接近的三数之和
- LeetCode16-最接近的三数之和
- 【Leetcode】16. 最接近的三数之和
- leetcode 16 最接近的三数之和
- [LeetCode] 16. 3Sum Closest 最接近的三数之和 @python
- #16. 最接近的三数之和-------中等
- LeetCode 16 3Sum Closest 找出最接近指定target的三个数的和
- Leetcode=最接近的三数之和
- leetcode第16题,最接近的三数之和,python实现
- [LeetCode] 16. 3Sum Closest 最近三数之和
- LeetCode刷题-最接近的三数之和