当前位置:网站首页>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;
}
}
边栏推荐
猜你喜欢
[Excel knowledge and skills] Convert numeric format numbers to text format
How engineers treat open source
Web-based meal ordering system in epidemic quarantine area
③ 关系数据库标准语言SQL 数据查询(SELECT)
构建资源的弹性伸缩
异常:try catch finally throws throw
【C语言】探索数据的存储(整形篇)
Introduction to Qt (6) - Implementation of the lottery system
[数据可视化] 图表设计原则
嵌入式软件打log的一些心得
随机推荐
Where can I download IEEE papers?
如何破坏Excel文件,让其显示文件已损坏方法
微信小程序获取当前页面的url和参数
SAP ABAP JSON 格式数据处理
networkmanager无法打开
构建资源的弹性伸缩
力扣------用栈操作构建数组
C#使用计时器
如何做到构建的提速,再提速
深度解析volatile关键字(保证够全面)
[21-day learning challenge - kernel notes] (5) - devmem read and write register debugging
3d打印出现stl文件物体不是流形,意味着不是水密体...解决办法
【.NET Core】使用 NPOI 读写Excel 文件
如何做专利挖掘,关键是寻找专利点,其实并不太难
How to do patent mining, the key is to find patent points, in fact, it is not too difficult
只会懒汉式和饿汉式 你还不懂单例模式!
Pagoda Test-Building PHP Online Mock Exam System
“蔚来杯“2022牛客暑期多校训练营2 DGHJKL题解
ADC和DAC记录
91.(cesium之家)cesium火箭发射模拟