Untitled
import java.util.*; public class KthLargestNumber { public String kthLargestNumber(String[] nums, int k) { // Step 1: Use a min-heap with a custom comparator PriorityQueue<String> minHeap = new PriorityQueue<>((a, b) -> { if (a.length() != b.length()) { return Integer.compare(a.length(), b.length()); // Compare by length } return a.compareTo(b); // Compare lexicographically }); // Step 2: Add elements to the heap for (String num : nums) { minHeap.offer(num); if (minHeap.size() > k) { minHeap.poll(); // Remove the smallest element } } // Step 3: The root of the heap is the k-th largest number return minHeap.poll(); } public static void main(String[] args) { KthLargestNumber solution = new KthLargestNumber(); // Example 1 String[] nums1 = {"3", "6", "7", "10"}; int k1 = 4; System.out.println(solution.kthLargestNumber(nums1, k1)); // Output: "3" // Example 2 String[] nums2 = {"2", "21", "12", "1"}; int k2 = 3; System.out.println(solution.kthLargestNumber(nums2, k2)); // Output: "2" // Example 3 String[] nums3 = {"0", "0"}; int k3 = 2; System.out.println(solution.kthLargestNumber(nums3, k3)); // Output: "0" } }
Leave a Comment