Leetcode: 3Sum Closest
2014-03-03 21:36
357 查看
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.
比较简单,O(n^2)时间复杂度。
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).
比较简单,O(n^2)时间复杂度。
class Solution { public: int threeSumClosest(vector<int> &num, int target) { int size = num.size(); if (size < 3) { return target; } sort(num.begin(), num.end()); int sum, closet_sum = num[0] + num[1] + num[2]; for (int i = 0; i < size; ++i) { for (int j = i + 1, k = size - 1; j < k;) { sum = num[i] + num[j] + num[k]; if (sum < target) { ++j; } else if (sum > target) { --k; } else { return sum; } if (abs(sum - target) < abs(closet_sum - target)) { closet_sum = sum; } } } return closet_sum; } };
相关文章推荐
- leetcode 16. 3Sum Closest
- 【C++】【LeetCode】15. 3Sum & 16. 3Sum Closest & 18. 4Sum
- [Leetcode]_16 3Sum Closest
- [leetcode] 3Sum Closest
- LeetCode解题报告—— Container With Most Water & 3Sum Closest & Letter Combinations of a Phone Number
- 【leetcode】3Sum Closest
- Leetcode16. 3Sum Closest
- LeetCode 3Sum Closest
- LeetCode 3Sum Closest
- leetcode --3Sum Closest
- LeetCode——3Sum Closest
- 【LeetCode】16. 3Sum Closest
- leetcode 15. 3sum && 16. 3Sum Closest && 18. 4Sum
- LeetCode 16. 3Sum Closest
- Leetcode_3Sum Closest
- [LeetCode16]3Sum Closest
- leetcode题解-16. 3Sum Closest
- 3Sum Closest[leetcode]
- [leetcode]16. 3Sum Closest
- [leetcode 15] 3sum && [leetcode 16] 3sum closest