当前位置:网站首页>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;
}
}
边栏推荐
猜你喜欢

Apache Commons Configuration远程代码执行漏洞(CVE-2022-33980)分析&复现

Go项目配置管理神器之viper使用详解

Pagoda Test-Building PHP Online Mock Exam System

地下管廊可视化管理系统搭建

异常:try catch finally throws throw

嵌入式软件打log的一些心得

百战RHCE(第四十八战:运维工程师必会技-Ansible学习3-构建Ansible清单)

微信小程序通过URL Scheme动态的渲染数据

BEVDepth: Acquisition of Reliable Depth for Multi-view 3D Object Detection 论文笔记

C# using timer
随机推荐
Web APIs BOM - A Comprehensive Case of Operating Browsers
“蔚来杯“2022牛客暑期多校训练营4 ADHK题解
HW-蓝队工作流程(1)
[Excel knowledge and skills] Convert text numbers to numeric format
sed of the Three Musketeers of Shell Programming
Introduction to Qt (6) - Implementation of the lottery system
异常和异常处理机制
SAS data processing technology (1)
【pypdf2】安装、读取和保存、访问页面、获取文本、读写元数据、加密解密
CF1427F-Boring Card Game【贪心】
Dump文件生成,内容,以及分析
[数据可视化] 图表设计原则
【mysql】mysql分别按年/月/日/周分组统计数据
How to check if the online query suddenly slows down
Pico 4更多参数曝光:Pancake+彩色透视,还有Pro版本
YOLOv5的Tricks | 【Trick12】YOLOv5使用的数据增强方法汇总
Pagoda Test-Building PHP Online Mock Exam System
BEVDepth: Acquisition of Reliable Depth for Multi-view 3D Object Detection 论文笔记
ArcGIS Pro 创建tpk
How to easily obtain the citation format of references?