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. 电话号码的字母组合
> 简洁易懂讲清原理,讲不清你来打我~ 输入字符串,输出对应整数 
基于查询的删除API 基于查询的删除API允许开发者基于查询删除一个或者多个索引.一个或者多个类型.下面是一个例子. import static org.elasticsearch.index.que ...
- windows server 文件夹和搜索选项被禁用了
当我们需要调整 windows 文件夹相关的配置时,却发现“文件夹和搜索选项”被禁用了,下图是恢复正常的情况.被禁用时显示灰色,不能点击. 下面给出解决步骤: 打开“组策略”. 然后依次展开“用户配置 ...
- windows API 第13篇 MoveFileEx
上一篇介绍了MoveFile,这次分析MoveFileEx,它是MoveFile的扩展函数,功能还要更加强大些.先看定义: BOOL WINAPI MoveFileEx( _In_ LPCTS ...
- win8 风格框架
http://metroui.org.ua/挺不错 bootstrap 系列的.
- [转]10 Tips for Learning a New Technology
We live in a very exciting time. Never before has education been so cheaply available to the masses ...
- sqlserver 创建用户 sp_addlogin
创建新的 Microsoft® SQL Server™ 登录,使用户得以连接使用 SQL Server 身份验证的 SQL Server 实例. 语法: sp_addlogin [ @loginam ...