当前位置:网站首页>16. 最接近的三数之和
16. 最接近的三数之和
2022-08-10 01:33:00 【happykoi】
16. 最接近的三数之和
日期:2022/8/9
题目描述:给你一个长度为 n 的整数数组 nums 和 一个目标值 target。请你从 nums 中选出三个整数,使它们的和与 target 最接近。
返回这三个数的和。
假定每组输入只存在恰好一个解。
示例:
输入:nums = [-1,2,1,-4], target = 1
输出:2
解释:与 target 最接近的和是 2 (-1 + 2 + 1 = 2) 。
输入:nums = [0,0,0], target = 1
输出:0
思路:
和0差不多,多了一步用Val存储要返回的值
代码+解析:
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
sort(nums.begin(),nums.end());
int val = nums[0]+nums[1]+nums[2];
for(int start=0; start<nums.size()-2; start++){
int index = start+1;
int end = nums.size()-1;
while(index<end){
int sum = nums[start]+nums[index]+nums[end];
if(abs(sum-target)<abs(val-target)) val = sum;
if(sum < target){
index++;
}
else if(sum > target){
end--;
}else{
return target;
}
}
}
return val;
}
};
边栏推荐
- GB28181 sip和RTSP(Real-Time Streaming Protocol)实时流控制协议
- Web性能测试模型小结
- Unity vertex animation
- 进程管理和任务管理
- hint: Updates were rejected because the tip of your current branch is behind hint: its remote counte
- [转] Typora_Markdown_图片标题(题注)
- 【机器学习】随机森林、AdaBoost、GBDT、XGBoost从零开始理解
- 22.括号生成
- RESOURCE_EXHAUSTED: etcdserver: mvcc: database space exceeded
- 【内存管理概述 Objective-C语言】
猜你喜欢
随机推荐
[转] Typora_Markdown_图片标题(题注)
空间复杂度为O(1)的归并排序
2022年8月8日-2022年8月15日,ue4视频教程+插件源码()
你有对象类,我有结构体,Go lang1.18入门精炼教程,由白丁入鸿儒,go lang结构体(struct)的使用EP06
volatile 关键字(修饰符 volatile 告诉编译器,变量的值可能以程序未明确指定的方式被改变)
跳房子游戏
mstsc/Mstsc (Microsoft terminal services client)远程桌面连接
In the 2022 gold, nine, silver and ten work tide, how can I successfully change jobs and get a high salary?
openpose脚部标注问题梳理
3438. 数制转换
基于设计稿识别的可视化低代码系统实践
gbase 8a数据库如何查看数据或数据文件是否正常?
C# rounding MidpointRounding.AwayFromZero
首次在我们的centos上安装MySQL
在蓝图中给组件动态加子Actor组件
【wpf】自定义事件总结(Action, EventHandler)
夏克-哈特曼波前传感器
【内存管理概述 Objective-C语言】
hint: Updates were rejected because the tip of your current branch is behind hint: its remote counte
OptiFDTD应用:纳米盘型谐振腔等离子体波导滤波器







![[LeetCode] Find the sum of the numbers from the root node to the leaf node](/img/1c/6c627e17a60f424601226504f4ff36.png)
