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. 电话号码的字母组合
> 简洁易懂讲清原理,讲不清你来打我~ 输入字符串,输出对应整数 : 并发总结 part 1 死锁与活跃度[转]
死锁与活跃度 前面谈了很多并发的特性和工具,但是大部分都是和锁有关的.我们使用锁来保证线程安全,但是这也会引起一些问题. 锁顺序死锁(lock-ordering deadlock):多个线程试图通 ...
- 《DSP using MATLAB》Problem 8.17
代码: %% ------------------------------------------------------------------------ %% Output Info about ...
- java linkedlist和arraylist添加元素时性能比较
- python configparser模块详解
此模块提供了一个实现基本配置语言的类 首先来看一个非常基本的配置文件,如下所示格式: [DEFAULT] ServerAliveInterval = 45 Compression = yes Comp ...
- [计蒜之道2019 复赛 A]外教 Michale 变身大熊猫
[计蒜之道2019 复赛 A]外教 Michale 变身大熊猫 Online Judge:2019计蒜之道 复赛 A Label:LIS+线段树.树状数组+快速幂(模逆元) 题目描述 题解: pre. ...
- day 71作业
作业: url配置 urlpatterns = [ url(r'^v2/cars/$',views.CarAPIView.as_view()), url(r'^v2/cars/(?P<pk> ...
- xshell上传文件到linux
z,sz是Linux/Unix同Windows进行ZModem文件传输的命令行工具. 优点就是不用再开一个sftp工具登录上去上传下载文件. sz:将选定的文件发送(send)到本地机器 rz:运行该 ...
- Ionic login简单登录页面
1.login.html <ion-view view-title="登录" hide-nav-bar="true"> <div class= ...
- scp免密码拉去方法
# scp命令免密码vi /etc/hosts.allow新增行sshd:61.174.9.92:allow 拷贝/root/.ssh/id_rsa.pub到备份机,重命名为/root/.ssh/au ...
- 前端面试题之一HTML
一.doctype作用? 严格模式与混杂模式如何区分?它们有何意义? (1)<!doctype>声明位于文档中的最前面的第一行,其作用告知浏览器用什么标准解析这个文档,并以浏览器支持的最高 ...