c_cpp 16. 3Sum Closest- Med - 2018.11.2
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 16. 3Sum Closest- Med - 2018.11.2相关的知识,希望对你有一定的参考价值。
class Solution {
public:
// 快排
void sort(vector<int>& nums, int left, int right) {
if (left >= right) {
return;
}
int i = left;
int j = right;
int tmp = nums[left];
while (i < j) {
// j找小于tmp的数
while (nums[j] >= tmp
&& i < j) {
j--;
}
// i找小于tmp的数
while (nums[i] <= tmp
&& i < j) {
i++;
}
// i和j的值互换
if (i < j) {
int t = nums[i];
nums[i] = nums[j];
nums[j] = t;
}
}
nums[left] = nums[i];
nums[i] = tmp;
sort(nums, left, i-1);
sort(nums, i+1, right);
}
int threeSumClosest(vector<int>& nums, int target) {
float re = INT_MAX;
int left = 0;
int right = 0;
int target_new;
sort(nums, 0, nums.size()-1);
for (int i = 0; i < nums.size(); i++) {
left = i + 1;
right = nums.size()-1;
target_new = target - nums[i];
while (left < right) {
int tmp = nums[i] + nums[left] + nums[right];
if (nums[left] + nums[right] == target_new) {
return target;
} else if (nums[left] + nums[right] > target_new) {
right--;
} else {
left++;
}
re = abs(re-target) > abs(tmp-target) ? tmp : re;
}
}
return re;
}
};
以上是关于c_cpp 16. 3Sum Closest- Med - 2018.11.2的主要内容,如果未能解决你的问题,请参考以下文章
16. 3Sum Closest
16. 3Sum Closest
LeetCode(16):3Sum Closest
Leetcode 16. 3Sum Closest
java 16. 3Sum Closest(#)。java
java 16. 3Sum Closest(#)。java