|
1 | 1 | /// Source : https://leetcode.com/problems/find-k-th-smallest-pair-distance/description/
|
2 | 2 | /// Author : liuyubobobo
|
3 |
| -/// Time : 2017-10-28 |
| 3 | +/// Time : 2022-06-14 |
4 | 4 |
|
5 | 5 | #include <iostream>
|
6 | 6 | #include <vector>
|
7 | 7 | #include <algorithm>
|
8 |
| -#include <set> |
9 | 8 |
|
10 | 9 | using namespace std;
|
11 | 10 |
|
12 |
| -/// Time Complexity: O(nlogn + n^2 + W) |
13 |
| -/// Space Complexity: O(W), where W = max(nums) - min(nums) |
| 11 | + |
| 12 | +/// Binary Search |
| 13 | +/// Time Complexity: O(log(max_dis) * nlogn) |
| 14 | +/// Space Complexity: O(1) |
14 | 15 | class Solution {
|
15 | 16 | public:
|
16 | 17 | int smallestDistancePair(vector<int>& nums, int k) {
|
17 | 18 |
|
18 |
| - int dis[1000000]; |
19 |
| - for(int i = 0 ; i < 1000000 ; i ++) |
20 |
| - dis[i] = 0; |
| 19 | + int n = nums.size(); |
21 | 20 |
|
22 | 21 | sort(nums.begin(), nums.end());
|
23 |
| - for(int i = 0 ; i < nums.size() ; i ++) |
24 |
| - for(int j = i + 1 ; j < nums.size() ; j ++){ |
25 |
| - //cout << nums[j] - nums[i] << endl; |
26 |
| - dis[nums[j]-nums[i]] ++; |
27 |
| - } |
28 |
| - |
29 |
| - int index = 0; |
30 |
| - for(int i = 0 ; i < 1000000 ; i ++){ |
31 |
| - index += dis[i]; |
32 |
| - if(k <= index) |
33 |
| - return i; |
| 22 | + int l = 0, r = nums.back() - nums[0]; |
| 23 | + while(l < r){ |
| 24 | + int d = (l + r) / 2; |
| 25 | + if(dis_cnt_less_than_or_equal_to(n, nums, d) >= k) r = d; |
| 26 | + else l = d + 1; |
34 | 27 | }
|
| 28 | + return l; |
| 29 | + } |
| 30 | + |
| 31 | +private: |
| 32 | + int dis_cnt_less_than_or_equal_to(int n, const vector<int>& nums, int d){ |
35 | 33 |
|
36 |
| - return -1; |
| 34 | + int cnt = 0; |
| 35 | + for(int i = 0; i < n; i ++){ |
| 36 | + auto iter = upper_bound(nums.begin(), nums.end(), nums[i] + d); |
| 37 | + cnt += iter - nums.begin() - i - 1; |
| 38 | + } |
| 39 | + return cnt; |
37 | 40 | }
|
38 | 41 | };
|
39 | 42 |
|
| 43 | + |
40 | 44 | int main() {
|
41 | 45 |
|
42 |
| - int nums1[] = {1, 3, 1}; |
43 |
| - int k1 = 1; |
44 |
| - vector<int> vec1(nums1, nums1 + sizeof(nums1)/sizeof(int)); |
45 |
| - cout << Solution().smallestDistancePair(vec1, k1) << endl; |
| 46 | + vector<int> nums1 = {1, 3, 1}; |
| 47 | + cout << Solution().smallestDistancePair(nums1, 1) << endl; |
46 | 48 | // 0
|
47 | 49 |
|
48 |
| - // --- |
| 50 | + vector<int> nums2 = {1, 1, 1}; |
| 51 | + cout << Solution().smallestDistancePair(nums2, 2) << endl; |
| 52 | + // 0 |
49 | 53 |
|
50 |
| - int nums2[] = {1, 6, 1}; |
51 |
| - int k2 = 3; |
52 |
| - vector<int> vec2(nums2, nums2 + sizeof(nums2)/sizeof(int)); |
53 |
| - cout << Solution().smallestDistancePair(vec2, k2) << endl; |
| 54 | + vector<int> nums3 = {1, 6, 1}; |
| 55 | + cout << Solution().smallestDistancePair(nums3, 3) << endl; |
54 | 56 | // 5
|
55 | 57 |
|
56 | 58 | return 0;
|
|
0 commit comments