LeetCode刷题-最接近的三数之和
2019-03-11 09:06
375 查看
最接近的三数之和
题目
给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。
样例
- 给定数组 nums = [-1,2,1,-4], 和 target = 1.
与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2).
Code
int threeSumClosest(vector<int>& nums, int target) { int result=0; int min_gap=INT_MAX; sort(nums.begin(), nums.end()); for(auto a=nums.begin(); a!=prev(nums.end(),2); ++a) { auto b=next(a); auto c=prev(nums.end()); while(b<c) { const int sum=*a + *b + *c; const int gap = abs(sum-target); if(gap<min_gap) { result=sum; min_gap=gap; } if(sum<target) { ++b; } else { --c; } } } return result; }
相关文章推荐
- LeetCode16.最接近的三数之和
- LeetCode16. python实现:最接近的三数之和问题☆☆
- 【PHP解法==LeetCode查找类型问题2(N数之和)】15.三数之和 && 16.最接近的三数之和 && 18.四数之和 && 454.四数相加II
- 【Leetcode】16. 最接近的三数之和
- LeetCode- 16. 最接近的三数之和 (Medium)python和c++实现
- LeetCode 16. 3Sum Closest. (最接近的三数之和)
- [LeetCode] 16. 3Sum Closest 最接近的三数之和 @python
- leetcode 16 最接近的三数之和
- LeetCode——16. 最接近的三数之和
- leetcode16---最接近的三数之和
- leetcode 16. 最接近的三数之和(Java版)
- 最接近的三数之和 - LeetCode
- leetcode第16题,最接近的三数之和,python实现
- Leetcode刷题38-16.最接近的三数之和(C++)
- LeetCode题解(python)-16. 最接近的三数之和
- LeetCode 16. 最接近的三数之和
- 【LeetCode-面试算法经典-Java实现】【016-3 Sum Closest(最接近的三个数的和)】
- LeetCode OJ-16.3Sum Closest(最接近三数和)
- leetcode-java.T016_threeSumClosest---给定包含n个整数数组S,找到S中的三个整数,从而使之和最接近给定的数,返回三个整数的总和.
- LeetCode 16 3Sum Closest (最接近target的3个数之和)