当前位置:网站首页>16. 最接近的三数之和
16. 最接近的三数之和
2022-08-11 00:26:00 【小卢要刷力扣题】
前言
给你一个长度为 n 的整数数组 nums 和 一个目标值 target。请你从 nums 中选出三个整数,使它们的和与 target 最接近。
返回这三个数的和。
假定每组输入只存在恰好一个解。
示例 1:
输入:nums = [-1,2,1,-4], target = 1
输出:2
解释:与 target 最接近的和是 2 (-1 + 2 + 1 = 2) 。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/3sum-closest
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题思路
跟三数之和思路差不多,使用双指针
重点是如何判断差值的距离
使用Math.abs(target-三个数的和)越小,距离就越近
先给数组排序
固定好i,
在i+1到n-1的范围找出sum
如果sum>target,那么r–,
否则l++
代码
class Solution {
public int threeSumClosest(int[] nums, int target) {
int n=nums.length;
Arrays.sort(nums);
int ans=Integer.MAX_VALUE;
for(int i=0;i<n-2;i++){
int l=i+1;
int r=n-1;
while(l<r){
int sum=nums[i]+nums[l]+nums[r];
if(sum==target){
return sum;
}
if(Math.abs(target-sum)<=Math.abs(target-ans)){
ans=nums[i]+nums[l]+nums[r];
}
if(sum>target){
r--;
}else{
l++;
}
// 排除相同的数
// if (sum > target) {
// int r0 = r - 1;
// while (l < r0 && nums[r0] == nums[r]) {
// --r0;
// }
// r = r0;
// } else {
// int l0 = l + 1;
// while (l0 < r && nums[l0] == nums[l]) {
// ++l0;
// }
// l = l0;
// }
}
}
return ans;
}
}
边栏推荐
- 使用 BeanUtils 做属性拷贝,性能有点拉胯!
- 15. Interceptor - HandlerInterceptor
- Design and Realization of Employment Management System in Colleges and Universities
- networkmanager无法打开
- [Excel knowledge and skills] Convert numeric format numbers to text format
- input输入框超出部分用省略号表示以及判断内容是否有超出(PC端)
- YOLOv5的Tricks | 【Trick11】在线模型训练可视化工具wandb(Weights & Biases)
- 2022下半年软考「高项」易混淆知识点汇总(2)
- 【openpyxl】只读模式、只写模式
- 分库分表ShardingSphere-JDBC笔记整理
猜你喜欢
ArcGIS Pro 创建tpk
15. Interceptor - HandlerInterceptor
HW-常见攻击方式和漏洞原理(2)
How to do patent mining, the key is to find patent points, in fact, it is not too difficult
微信小程序自定义navigationBar
学习Apache ShardingSphere解析器源码(一)
构建资源的弹性伸缩
[数据可视化] 图表设计原则
有哪些可以投稿软件工程/系统软件/程序设计语言类外文期刊、会议?
Is there a way out in the testing industry if it is purely business testing?
随机推荐
关于编程本质那些事
构建检测,无规矩不成方圆
Jvm. Profiling tools (jconsole, jvisualvm, arthas, jprofiler, mat)
云原生-FRP内网穿透(详解)使用云服务器将内网集群服务暴露至公网(二)
容器技术真的是环境管理的救星吗?
input输入框超出部分用省略号表示以及判断内容是否有超出(PC端)
13. Content Negotiation
10. 接收参数相关注解
nodejs项目连接mysql数据库
3. 容器功能
CF1286E-Fedya the Potter Strikes Back【KMP,RMQ】
YOLOv5的Tricks | 【Trick13】YOLOv5的detect.py脚本的解析与简化
Server Tips
rhel7.0解决yum无法使用(system is not registered to Red Hat Subscription Management)
2. Dependency management and automatic configuration
Difference Between Image Recognition and Semantic Segmentation
只会懒汉式和饿汉式 你还不懂单例模式!
两个数组的交集
分库分表ShardingSphere-JDBC笔记整理
IEEE的论文哪里可以下载?