LeetCode题解——3Sum Closest
题目:
给定一个数组,和一个指定的值,找出数组中3个数,它的和最接近这个指定值,并返回这个和。
解法:
和上一题找3个数的和为0一样,先排序再遍历,这一次不需要记录路径。
代码:
class Solution {
public:
int threeSumClosest(vector<int> &num, int target) {
int result, min_gap = INT_MAX;
sort(num.begin(), num.end()); //先排序 for(int a = ; a < num.size() - ; ++a)
for(int b = a + , c = num.size() - ; b < c; )
{
int sum = num[a] + num[b] + num[c];
int gap = sum - target; if(gap == ) //找到相等的值,直接返回
return target; if(abs(gap) < min_gap)
{
min_gap = abs(gap);
result = sum;
} if(sum > target)
--c;
else
++b;
}
return result;
}
};
LeetCode题解——3Sum Closest的更多相关文章
- LeetCode 16. 3Sum Closest(最接近的三数之和)
LeetCode 16. 3Sum Closest(最接近的三数之和)
- Leetcode 16. 3Sum Closest(指针搜索)
16. 3Sum Closest Medium 131696FavoriteShare Given an array nums of n integers and an integer target, ...
- 【leetcode】3Sum Closest
3Sum Closest Given an array S of n integers, find three integers in S such that the sum is closest t ...
- [Leetcode][016] 3Sum Closest (Java)
题目: https://leetcode.com/problems/3sum-closest/ [标签]Array; Two Pointers [个人分析] 这道题和它的姊妹题 3Sum 非常类似, ...
- LeetCode(16)题解--3Sum Closest
https://leetcode.com/problems/3sum-closest/ 题目: Given an array S of n integers, find three integers ...
- LeetCode (13): 3Sum Closest
https://leetcode.com/problems/3sum-closest/ [描述] Given an array S of n integers, find three integers ...
- LeetCode——16. 3Sum Closest
一.题目链接:https://leetcode.com/problems/3sum-closest/ 二.题目大意: 给定一个数组A和一个目标值target,要求从数组A中找出3个数来,使得这三个数的 ...
- [LeetCode] 16. 3Sum Closest 最近三数之和
Given an array nums of n integers and an integer target, find three integers in nums such that the s ...
- Leetcode 16. 3Sum Closest
Given an array S of n integers, find three integers in S such that the sum is closest to a given num ...
随机推荐
- java 泛型类
Java泛型中的标记符含义: E - Element (在集合中使用,因为集合中存放的是元素) T - Type(Java 类) K - Key(键) V - Value(值) N - Numbe ...
- python 利用smtp发送邮件,html格式
def send_mail(to_list, sub, context):#sentmail to the maillist ''' to_list: 发送给谁 sub: 主题 context: 内容 ...
- python基础 - 文件读写
完成功能: 从指定位置读文件到控制台 #! /usr/bin/python # coding=utf- 方法一. try: f = open ('/root/python/file/001.txt', ...
- linq to Entity 数据库除了有主键还有唯一索引,是不是不能更新
数据库建了一个唯一索引,使用linq to ef更新的时候,老是报,索引建冲突,,坑了我一上午,最后把索引删了
- zlib用法说明
1. 如何获得zlib zlib的主页是:http://www.zlib.net/ 2. 用VC++6.0打开 把 下载的源代码解压打开,VC6.0的工程已经建好了,在\projects\visual ...
- Math.sqrt
java.lang.Math.sqrt(double a) 返回正确舍入的一个double值的正平方根.特殊情况: 如果参数是NaN或小于为零,那么结果是NaN. 如果参数是正无穷大,那么结果为正无穷 ...
- 装个Redmine真是麻烦啊
弄个大半天终于看到这个界面出来了,不容易啊
- windows2003 IIS6网络负载平衡设置
问题 随着计算机技术的不断发展,单台计算机的性能和可靠性越来越高.但现实中还是有许多应用是单台计算机难以达到,例如: 1.银行存储用户数据的数据库服务器必须保证24小时不间断的运转,并在发生严重硬件故 ...
- Material Design 设计--阴影的重要性
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_cont ...
- C#进程启动程序,并禁止原窗口操作
Process myProcess = new Process(); myProcess.StartInfo.FileName = exeName; myP ...