719 Find K-th Smallest Pair Distance
1. Question
Given an integer array, return the k-th smallest distance among all the pairs. The distance of a pair (A, B) is defined as the absolute difference between A and B.
Example 1:
Input:
nums = [1,3,1]
k = 1
Output: 0
Explanation:
Here are all the pairs:
(1,3) -> 2
(1,1) -> 0
(3,1) -> 2
Then the 1st smallest distance pair is (1,1), and its distance is 0.Note:
2 <= len(nums) <= 10000.0 <= nums[i] < 1000000.1 <= k <= len(nums) * (len(nums) - 1) / 2.
2. Implementation
(1) Binary Search
思路: 这题的居然思路和 Kth Smallest Element in a Sorted Matrix一样,不同的是searchAndCount的逻辑不同,实在没想到。对于这种求第K小/大的题目中,如果其中包含某些带有顺序属性的性质,我们可以用二分法求出结果
(2) Heap (TLE)
3. Time & Space Complexity
Binary Search: 时间复杂度O(nlogn + (n^2) *logD), 其中D是数组中最大的diff的值,因为我们是在【0, maxDiff】这个space里进行二分搜索的
Heap: 时间复杂度O(nlogn + klogn), 空间复杂度O(n)
Last updated
Was this helpful?