16. 3Sum Closest
2016-07-22 16:18
323 查看
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.
只用返回最接近的和,没有具体数字,也没有下标要求,还只有唯一确定解,真是不错的条件。
但其实跟之前的一样,也是只需要找出不同的值来就行了。
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).
只用返回最接近的和,没有具体数字,也没有下标要求,还只有唯一确定解,真是不错的条件。
但其实跟之前的一样,也是只需要找出不同的值来就行了。
int threeSumClosest(vector<int>& nums, int target) { int n = nums.size(); sort(nums.begin(), nums.end()); int i, temp_sum = 0, sum = nums[0] + nums[1] + nums[2]; // sum初始化不能给定0之类的,否则会干扰判断,必须是实际存在的组合求和 for (i = 0; i < n - 2; i++) { if (i > 0 && nums[i] == nums[i - 1]) continue; int start = i + 1; int end = nums.size() - 1; while (start < end) { temp_sum = nums[i] + nums[start] + nums[end]; if (abs(temp_sum - target) < abs(sum - target)) sum = temp_sum; if (temp_sum == target) { return sum; } else { if (temp_sum < target) start++; else end--; } } } return sum; }
相关文章推荐
- NYOJ219-An problem about date
- python性能测试脚本
- SQL语句优化
- 称砝码******
- Volley 源码解析
- C#无边框移动
- 定义一个只能在堆上(栈上)生成对象的类
- Caused by: java.lang.IncompatibleClassChangeError: class org.springframework.scheduling.quartz.CronTriggerBean has interface org.quartz.CronTrigger as super class
- 【渗透测试学习平台】 web for pentester -8.XML
- 【贪心】马拉松接力赛
- win7远程凭据无法工作
- [转]架构蓝图--软件架构 "4+1" 视图模型
- C#无边框移动
- 构造性证明
- 1088. Rational Arithmetic (20)
- [JQ权威指南]使用JQ读取JSON数据
- CocoaLumberjack使用以及日志文件获取
- HDU 1026 Ignatius and the Princess I
- odoo同一个表,怎么从不同菜单进去后显示不同的form
- 我的第一篇博客