LeetCode刷题(C++)——3Sum Closest(Medium)
2017-05-04 20:24
525 查看
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.
思路:此题类似于3Sum这道题,在3Sum那道题的基础上稍微修改一下即可http://blog.csdn.net/yf_li123/article/details/71176581
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)
思路:此题类似于3Sum这道题,在3Sum那道题的基础上稍微修改一下即可http://blog.csdn.net/yf_li123/article/details/71176581
class Solution { public: int threeSumClosest(vector<int>& nums, int target) { sort(nums.begin(), nums.end()); int closest = INT_MAX; int ans = 0; for (int start = 0; start < nums.size();start++) { int i = start + 1; int j = nums.size() - 1; while (i < j) { int sum = nums[i] + nums[j] + nums[start]; if (sum == target) return target; else if (sum < target) { if ((target - sum) < closest) { closest = target - sum; ans = sum; } while (i + 1 < nums.size() && nums[i] == nums[i + 1]) i++; i++; } else { if ((sum - target) < closest) { closest = sum - target; ans = sum; } while (j - 1 >= 0 && nums[j] == nums[j - 1]) j--; j--; } } while (start + 1 < nums.size() && nums[start] == nums[start + 1]) start++; } return ans; } };
相关文章推荐
- leetcode刷题系列C++-3Sum Closest
- Leetcode 16[medium]--3Sum Closest
- 【C++】【LeetCode】15. 3Sum & 16. 3Sum Closest & 18. 4Sum
- [Leetcode 16, Medium] 3Sum Closest
- [LeetCode] 015. 3Sum (Medium) (C++/Java/Python)
- 【Leetcode】【Medium】3Sum Closest
- LeetCode刷题(C++)——3Sum(Medium)
- LeetCode-3Sum Closest
- 【LeetCode】3Sum Closest
- Leetcode:3Sum Closest
- LeetCode 3Sum 三个数和为零的集合 C++完整程序
- Leetcode: 3Sum Closest
- LeetCode | 3Sum Closest
- leetcode 57: 3Sum Closest
- 【leetcode】3Sum Closest
- LeetCode : 3Sum Closest
- [LeetCode]3Sum Closest
- leetcode 3Sum Closest
- [leetcode刷题系列]3Sum Closest
- leetcode: 3Sum Closest