Leetcode16.3Sum Closest最接近的三数之和
给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。
例如,给定数组 nums = [-1,2,1,-4], 和 target = 1. 与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2).
bool cmp1(int x, int y)
{
return x < y;
}
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target)
{
int len = nums.size();
sort(nums.begin(), nums.end(), cmp1);
int MIN = INT_MAX;
int res = 0;
for(int i = 0; i < len - 2; i++)
{
int low = i + 1;
int high = len - 1;
while(low < high)
{
int temp = nums[i] + nums[low] + nums[high];
if(temp == target)
{
MIN = 0;
res = target;
break;
}
else if(temp < target)
{
if(MIN > abs(target - temp))
{
MIN = abs(target - temp);
res = temp;
}
low++;
}
else
{
if(MIN > abs(target - temp))
{
MIN = abs(target - temp);
res = temp;
}
high--;
}
}
}
return res;
}
};
Leetcode16.3Sum Closest最接近的三数之和的更多相关文章
- LeetCode 16. 3Sum Closest(最接近的三数之和)
LeetCode 16. 3Sum Closest(最接近的三数之和)
- 【LeetCode】16. 3Sum Closest 最接近的三数之和
作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 个人公众号:负雪明烛 本文关键词:3sum, three sum, 三数之和,题解,lee ...
- [leetcode]16. 3Sum Closest最接近的三数之和
Given an array nums of n integers and an integer target, find three integers in nums such that the s ...
- 016 3Sum Closest 最接近的三数之和
Given an array S of n integers, find three integers in S such that the sum is closest to a given num ...
- Leetcode13. 罗马数字转整数Leetcode14. 最长公共前缀Leetcode15. 三数之和Leetcode16. 最接近的三数之和Leetcode17. 电话号码的字母组合
> 简洁易懂讲清原理,讲不清你来打我~ 输入字符串,输出对应整数  mysql本身不像oracle那样使用 rownum 来显示行号的功能.但是可以使用设置变量的方式来实现这一功能. mysql使用 @ 定义用户变量, ...
- css3之2D 转换
浏览器支持 表格中的数字表示支持该属性的第一个浏览器版本号. 紧跟在 -webkit-, -ms- 或 -moz- 前的数字为支持该前缀属性的第一个浏览器版本号. Chrome 和 Safari 要求 ...
- vue 报错:Cannot read property '_wrapper' of undefined
我的情况是@click="xx" ,而xx函数未定义
- Region服务器工作原理
- 使用ResponseEntity进行返回json数据
在最近的项目中,与上位机进行数据传输时,上位机需要服务器的响应得知服务器是否正常运行,数据是否正常发送 在最近的调试中我使用ResponseEntity<Map<String,Object ...
- zimage 和bzimage 有什么区别
在网络中,不少服务器采用的是Linux系统.为了进一步提高服务器的性能,可能需要根据特定的硬件及需求重新编译Linux内核.编译Linux 内核,需要根据规定的步骤进行,编译内核过程中涉及到几个重要的 ...
- JZOJ5822 【NOIP提高A组模拟2018.8.16】 量子纠缠
这是一道很巧妙的题目. 今早,我调了好久,终于将它切掉了-- 题目 Description Input 第一行包含一个正整数 m,代表操作数. 接下来 m 行,每行可能有以下形式: 1 s 代表将数字 ...