leetcode腾讯精选50-016
2019-05-22 00:30
260 查看
题目:https://leetcode-cn.com/problems/3sum-closest/
代码:class Solution {
public:
int threeSumClosest(vector& nums, int target) {
sort(nums.begin(), nums.end()); int size = nums.size(); //if (nums.front() > target) return nums[0] + nums[1] + nums[2]; //if (nums.back() < target) return nums[size - 1] + nums[size - 2] + nums[size - 3]; int res = nums[0] + nums[2] + nums[1]; for (int i = 0; i < nums.size(); i++) { int a = nums[i]; //if (a > target) break; int l = i + 1; int r = nums.size() - 1; if(l >=r) break; int tmp = nums[l] + nums[r] + a; while (l < r) { int sum = nums[l] + nums[r] + a; if ( abs(sum - target) < abs(tmp - target)) { tmp = sum; } if (nums[l] + nums[r] == target -a) { tmp = target; return target; } else if (nums[l] + nums[r] >target -a) { r--; } else { l++; } } if (abs(res - target)> abs(tmp - target)) res = tmp; } return res;
}
};
结果:
相关文章推荐
- leetcode NO.7 整数反转 腾讯精选练习50
- leetcode NO.2两数相加 腾讯精选练习50
- leetcode腾讯精选50-021
- Leetcode腾讯精选_编号:2 --python
- Leetcode腾讯精选_编号:206 --python
- Leetcode腾讯精选_编号:292 --python
- Leetcode腾讯精选_编号:4 --python
- Leetcode腾讯精选_编号:217 --python
- Leetcode腾讯精选_编号:344 --python
- Leetcode腾讯精选_编号:7 --python
- Leetcode腾讯精选_编号:9 --python
- Leetcode腾讯精选_编号:557 --python
- Leetcode腾讯精选_编号:11 --python
- Leetcode腾讯精选_编号:14 --python
- Leetcode腾讯精选_编号:20 --python
- Leetcode腾讯精选_编号:23 --python
- Leetcode腾讯精选_编号:26 --python
- Leetcode腾讯精选_编号:33 --python
- leetcode第二天 腾讯50题 14 最长前缀
- Leetcode腾讯精选_编号:43 --python