-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
3b33e64
commit cffe83c
Showing
1 changed file
with
31 additions
and
0 deletions.
There are no files selected for viewing
31 changes: 31 additions & 0 deletions
31
leetcode/problems/java/find-k-th-smallest-pair-distance.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
|
||
import java.util.Arrays; | ||
|
||
class Solution { | ||
public int smallestDistancePair(int[] numbers, int k) { | ||
Arrays.sort(numbers); | ||
int minDist = 0; | ||
int maxDistance = numbers[numbers.length - 1] - numbers[0]; | ||
|
||
while (minDist < maxDistance) { | ||
int mid = minDist + (maxDistance - minDist) / 2; | ||
int count = countPairsWithinDistance(numbers, mid); | ||
if (count < k) | ||
minDist = mid + 1; | ||
else | ||
maxDistance = mid; | ||
} | ||
return minDist; | ||
} | ||
|
||
private int countPairsWithinDistance(int[] numbers, int targetDistance) { | ||
int count = 0; | ||
int left = 0; | ||
for (int right = 1; right < numbers.length; right++) { | ||
while (numbers[right] - numbers[left] > targetDistance) | ||
left++; | ||
count += right - left; | ||
} | ||
return count; | ||
} | ||
} |