16. 3Sum Closest
来源:互联网 发布:乐视自行车软件 编辑:程序博客网 时间:2024/06/05 07:44
问题:
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.
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).
分析:首先可以对数组进行排序,其次计算离目标最近的三个数之和
该算法可以分两种情况:1、当target比数组的最小的数还小,排序后的数组中最小的三个数的和为最靠近target的和
2、其他情况下需要遍历找最靠近target的三个数的和。
代码:int threeSumClosest(vector<int>& nums, int target) {
int closestNum,sum;
sort(nums.begin(), nums.end());//数组排序
if (nums.size() < 3)//数组少于3个时返回0
return 0;
closestNum = nums[0] + nums[1] + nums[2];
if (target <= nums[0])//第一种情况
return closestNum;
for (int i = 0; i < nums.size() - 2; i++) {
int j = i + 1;
int k = nums.size - 1;
while (j < k) {
sum = nums[i] + nums[j] + nums[k];
if (abs(target - closestNum) > abs(target - sum)) {//当前单个数和李target更近时,令该和为最靠近target的和
closestNum = sum;
if (closestNum == target) return closestNum;
}
(sum > target) ? k-- : j++;
}
}
return closestNum;
};
- 16. 3Sum Closest
- 16. 3Sum Closest
- 16. 3Sum Closest
- 16. 3Sum Closest
- 16. 3Sum Closest
- 16. 3Sum Closest
- 16. 3Sum Closest
- 16. 3Sum Closest
- 16. 3Sum Closest
- 16. 3Sum Closest
- 16. 3Sum Closest
- 16. 3Sum Closest
- 16. 3Sum Closest
- 16. 3Sum Closest
- 16. 3Sum Closest
- 16. 3Sum Closest
- 16. 3Sum Closest
- 16. 3Sum Closest
- 服务器错误500 501 502 503 504 505 详解
- 杭电oj1231(动态规划最大连续子序列之和)
- 设计模式——装饰模式详解
- Java面试三
- 448. Find All Numbers Disappeared in an Array(c语言)
- 16. 3Sum Closest
- 【GLSL教程】(一)图形流水线
- JVM 如何创建Java对象
- 计算机图形图像处理 实验二
- STM32端口复用
- ddos一个思路
- 压缩图片的方式个人总结
- isight调用matlab专业模块
- MySql获取时间范围中的随机日期