The distance of a pair of integers a and b is defined as the absolute difference between a and b.
Given an integer array nums and an integer k,return the kth smallest distance among all the pairs nums[i]and nums[j] where 0<= i < j < nums.length.
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/find-k-th-smallest-pair-distance
The codes
#include<vector>#include<algorithm>#include<iostream>usingnamespace std;classSolution{public:intsmallestDistancePair(vector<int>& nums,int k){sort(nums.begin(), nums.end());int left =0;int right =*(nums.end()-1)-*nums.begin();while(left <= right){int mid =(left + right)/2;int cnt =0;for(int i =0; i < nums.size(); i++){int j =lower_bound(nums.begin(), nums.begin()+ i, nums[i]- mid)- nums.begin();
cnt += i - j;}if(cnt >= k){
right = mid -1;}else{
left = mid +1;}}return left;}};intmain(){
Solution s;
vector<int> nums ={1,3,1};int k =1;
cout <<"result: "<< s.smallestDistancePair(nums, k)<< endl;return0;}