The Find the Kth Largest Integer in the Array problem involves finding the K
th largest integer in an array of strings, where each string represents an integer. The comparison is based on numerical values.
This problem can be solved using a min-heap to track the top K
largest integers.
class Solution {
public String kthLargestNumber(String[] nums, int k) {
PriorityQueue<String> minHeap = new PriorityQueue<>(
(a, b) -> {
if (a.length() == b.length()) {
return a.compareTo(b); // Lexicographical comparison
}
return Integer.compare(a.length(), b.length()); // Compare by length
}
);
// Step 1: Add elements to the heap
for (String num : nums) {
minHeap.offer(num);
if (minHeap.size() > k) {
minHeap.poll(); // Remove the smallest element
}
}
// Step 2: The root of the heap is the Kth largest integer
return minHeap.peek();
}
}
O(N log K)
โ Adding and removing elements from the heap.O(N log K)
.Input: nums = ["3","6","7","10"], k = 2
Output: "7"
Explanation:
- The integers are [3, 6, 7, 10].
- The 2nd largest integer is "7".