当前位置:网站首页>【刷题篇】 找出第 K 小的数对距离
【刷题篇】 找出第 K 小的数对距离
2022-07-03 03:52:00 【m0_60631323】
一、题目
数对 (a,b) 由整数 a 和 b 组成,其数对距离定义为 a 和 b 的绝对差值。
给你一个整数数组 nums 和一个整数 k ,数对由 nums[i] 和 nums[j] 组成且满足 0 <= i < j < nums.length 。返回 所有数对距离中 第 k 小的数对距离。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/find-k-th-smallest-pair-distance
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
二、题解
2.1思路

2.2源码
返回值rightest的初始值设为-1,是为了一种特殊情况,就是给定的nums数组中的数据都是相同的,那么无论给定的K是多少,第K小的距离都是0,进入循环后rightest的值没有改变还是-1,最后返回-1+1=0,符合
public static int smallestDistancePair(int[] arr, int k) {
int n=arr.length;
if(n<2||k<1||k>(n*(n-1))>>1){
return -1;
}
Arrays.sort(arr);
int left=0;
int right=arr[n-1]-arr[0];
int mid=0;
int rightest=-1;
while (left<=right){
mid=(left+right)/2;
if(valid(arr,mid,k)){
rightest=mid;
left=mid+1;
}else {
right=mid-1;
}
}
return rightest+1;
}
public static boolean valid(int[] arr,int limit,int k){
int x=0;
for (int l=0,r=1;l<arr.length;r=Math.max(r,++l)){
while (r< arr.length&&(arr[r]-arr[l]<=limit)){
r++;
}
x+=r-l-1;
}
return x<k;
}
边栏推荐
- MongoDB簡介
- TCP, the heavyweight guest in tcp/ip model -- Kuige of Shangwen network
- js中#号的作用
- Shardingsphere dynamic data source
- 学会pytorch能干什么?
- FileZilla Client下載安裝
- How to move towards IPv6: IPv6 Transition Technology - Shangwen network quigo
- Commands related to the startup of redis under Linux server (installation and configuration)
- Role of JS No
- Arlo's thinking about himself
猜你喜欢

Makefile demo

pytorch怎么下载?pytorch在哪里下载?

Ffmpeg recording screen and screenshot

Leetcode: dynamic planning template

pytorch难学吗?如何学好pytorch?

How to download pytorch? Where can I download pytorch?

Summary of electromagnetic spectrum
![[embedded module] OLED display module](/img/c4/474f5ee580d132654fbd1a4cd53bab.jpg)
[embedded module] OLED display module

Error in compiled file: error: unmapped character encoding GBK

Ffmpeg one / more pictures synthetic video
随机推荐
错误 C2694 “void Logger::log(nvinfer1::ILogger::Severity,const char *)”: 重写虚函数的限制性异常规范比基类虚成员函数
[national programming] [software programming - Lecture Video] [zero foundation introduction to practical application]
npm : 无法将“npm”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保路径正确,然后再试一次。
毕设-基于SSM宠物领养中心
Recursion: quick sort, merge sort and heap sort
[Blue Bridge Road - bug free code] pcf8591 - code analysis of AD conversion
Wechat applet + Alibaba IOT platform + Hezhou air724ug built with server version system analysis
Hutool dynamically adds scheduled tasks
105. SAP UI5 Master-Detail 布局模式的联动效果实现明细介绍
User value is the last word in the competition of mobile phone market
golang xxx. Go code template
Captura下载安装及在Captura配置FFmpeg
TCP, the heavyweight guest in tcp/ip model -- Kuige of Shangwen network
2022 polymerization process examination questions and polymerization process examination skills
学会pytorch能干什么?
MongoDB复制集【主从复制】
如何迈向IPv6之IPv6过渡技术-尚文网络奎哥
C language hashtable/hashset library summary
C语言HashTable/HashSet库汇总
Half of 2022 is over, so we must hurry up