(leetcode学习)16. 最接近的三数之和
给你一个长度为
n
的整数数组nums
和 一个目标值target
。请你从nums
中选出三个整数,使它们的和与target
最接近。返回这三个数的和。
假定每组输入只存在恰好一个解。
示例 1:
输入:nums = [-1,2,1,-4], target = 1 输出:2 解释:与 target 最接近的和是 2 (-1 + 2 + 1 = 2) 。示例 2:
输入:nums = [0,0,0], target = 1 输出:0提示:
3 <= nums.length <= 1000
-1000 <= nums[i] <= 1000
-104 <= target <= 104
没什么好的思路,先暴力一下,打败10%
int threeSumClosest(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
int res, diff = INT_MAX, nums_len = nums.size();
if (target >= 3 * nums[nums_len - 1]) return nums[nums_len - 1] + nums[nums_len - 2] + nums[nums_len - 3];
if (target <= 3 * nums[0]) return nums[0] + nums[1] + nums[2];
for (int i = 0; i < nums_len; i++) {
if (i != 0 && nums[i] == nums[i - 1]) continue;
for (int j = i + 1; j < nums_len; j++) {
if (j != i + 1 && nums[j] == nums[j - 1]) continue;
int cur_diff = INT_MAX, cur_res;
for (int k = j + 1; k < nums_len; k++) {
if (abs(nums[i] + nums[j] + nums[k] - target) > cur_diff) break;
cur_diff = abs(nums[i] + nums[j] + nums[k] - target);
cur_res = nums[i] + nums[j] + nums[k];
}
if (cur_diff < diff) {
res = cur_res;
diff = cur_diff;
}
}
}
return res;
}
原文地址:https://blog.csdn.net/m0_54888411/article/details/140423356
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!