当前位置:网站首页>16. Sum of the nearest three numbers
16. Sum of the nearest three numbers
2022-08-11 00:34:00 【Xiao Lu wants to brush the force and deduct the question】
前言
给你一个长度为 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
著作权归领扣网络所有.商业转载请联系官方授权,非商业转载请注明出处.
解题思路
Similar to the idea of the sum of three,使用双指针
The point is how to judge the distance of the difference
使用Math.abs(target-三个数的和)越小,距离就越近
先给数组排序
固定好i,
在i+1到n-1range to find outsum
如果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++;
}
// Exclude the same numbers
// 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;
}
}
边栏推荐
- 镜头之滤光片---关于日夜两用双通滤光片
- 百战RHCE(第四十八战:运维工程师必会技-Ansible学习3-构建Ansible清单)
- 微信小程序自定义navigationBar
- 嵌入式软件打log的一些心得
- 14. Thymeleaf
- 两个数组的交集
- Software Testing Certificate (1) - Software Evaluator
- "NIO Cup" 2022 Nioke Summer Multi-School Training Camp 2 DGHJKL Problem Solution
- ① 数据库介绍 及 关系型数据库的关系代数表达式
- BEVDepth: Acquisition of Reliable Depth for Multi-view 3D Object Detection Paper Notes
猜你喜欢

Qt入门(六)——抽奖系统的实现

复制带随机指针的链表——LeetCode
![[GXYCTF2019]BabySQli](/img/8a/7500c0ee275d6ef8909553f34c99cf.png)
[GXYCTF2019]BabySQli

从0开始设计JVM ,忘记名词跟上思路一次搞懂

3d打印出现stl文件物体不是流形,意味着不是水密体...解决办法

异常:try catch finally throws throw

Only lazy and hungry. You still don't understand the singleton pattern!

使用mysql语句操作数据表(table)

报错:Client does not support authentication protocol requested by server; consider upgrading MySQL cli

Exceptions and exception handling mechanisms
随机推荐
J9 Digital Theory: DAO governance is more like an ecological process: governance is native to the network and continues to evolve
91.(cesium之家)cesium火箭发射模拟
[数据可视化] 图表设计原则
ArcGIS Pro 创建tpk
BEVDepth: Acquisition of Reliable Depth for Multi-view 3D Object Detection Paper Notes
构建资源的弹性伸缩
【pypdf2】合并PDF、旋转、缩放、裁剪、加密解密、添加水印
异常:try catch finally throws throw
electron -autoUpdater 更新
关于编程本质那些事
使用mysql语句操作数据表(table)
C#-委托的详细用法
给肯德基打工的调料商,年赚两亿
微信小程序通过URL Scheme动态的渲染数据
YOLOv5的Tricks | 【Trick11】在线模型训练可视化工具wandb(Weights & Biases)
百战RHCE(第四十八战:运维工程师必会技-Ansible学习3-构建Ansible清单)
networkmanager无法打开
【.NET Core】使用 NPOI 读写Excel 文件
【js】获取当前时间的前后n天或前后n个月(时分秒年月日都可)
Navicat 16-数据库工具