LeetCode 16 - 3Sum Closest
2015-05-19 21:11
393 查看
一、问题描述
Description:
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).
给定一个包含 n 个整数的数组,以及一个目标整数 target,在数组中找出三个数,使它们的和 与 target 的距离最小。返回这三个数的和。
假定每个输入一定有结果。
二、解题报告
同《LeetCode 15 - 3Sum》一样,本题我们也是要利用排序这个性质,来减少判断。思路:
先整体排一次序
然后遍历数组,固定一个元素,对其后的元素采用头尾指针。
若距离更小,更新距离与三个数之和。
否则,移动头指针或尾指针。
时间复杂度是O(n2),代码如下:
class Solution { public: int threeSumClosest(vector<int>& nums, int target) { sort(nums.begin(), nums.end()); // 排序 int distance = INT_MAX; // 记录距离 int sum = nums[0]+nums[1]+nums[2]; // 记录和 for(int i=0; i<nums.size()-2; ++i) { // 固定一个数字 int l = i+1; // 头指针 int r = nums.size()-1; // 尾指针 while(l < r) { // 如果距离更近,则更新 if(abs(nums[l]+nums[r]+nums[i]-target) < distance) { sum = nums[l]+nums[r]+nums[i]; distance = abs(nums[l]+nums[r]+nums[i]-target); } if(nums[l]+nums[r]+nums[i] == target) return sum; else if(nums[l]+nums[r]+nums[i] < target) ++l; else --r; } } return sum; } };
AC 时间 20ms。
LeetCode答案源代码:https://github.com/SongLee24/LeetCode
相关文章推荐
- leetcode16~3Sum Closest
- LeetCode_16---3Sum Closest
- [leetcode] 16. 3Sum Closest
- [leetcode] 16. 3Sum Closest 解题报告
- leetcode--16. 3Sum Closest
- LeetCode 16: 3Sum Closest
- LeetCode 16 3Sum Closest (最接近target的3个数之和)
- LeetCode-16-3Sum Closest(C语言实现)
- leetcode --16. 3Sum Closest
- LeetCode 16 3Sum Closest(最接近的3个数的和)
- LeetCode 16 3Sum Closest 找出最接近指定target的三个数的和
- [Leetcode] 16. 3Sum Closest 解题报告
- LeetCode | 16. 3Sum Closest 循环技巧题
- [leetcode] 16 3Sum Closest(数组)
- 【LeetCode】16_3Sum Closest
- [leetcode 16] 3Sum Closest
- leetcode 16: 3Sum Closest
- [leetcode] 16. 3Sum Closest
- LeetCode-16:3Sum Closest
- leetcode16:3Sum Closest