高级农民
- 积分
- 3979
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2017-12-21
- 最后登录
- 1970-1-1
|
看看是不是这样做的。- public class KthLargestInSortedArrays {
- public static int findKthLargest(int[] A, int[] B, int k) {
- int totalLength = A.length + B.length;
- int kthSmallest = totalLength - k + 1; // Convert kth largest to kth smallest
- return findKthSmallest(A, B, kthSmallest);
- }
- private static int findKthSmallest(int[] A, int[] B, int k) {
- int m = A.length, n = B.length;
- // Ensure A is the smaller array
- if (m > n) return findKthSmallest(B, A, k);
- int left = Math.max(0, k - n);
- int right = Math.min(k, m);
- while (left <= right) {
- int i = left + (right - left) / 2;
- int j = k - i;
- int Aleft = (i == 0) ? Integer.MIN_VALUE : A[i - 1];
- int Aright = (i == m) ? Integer.MAX_VALUE : A[i];
- int Bleft = (j == 0) ? Integer.MIN_VALUE : B[j - 1];
- int Bright = (j == n) ? Integer.MAX_VALUE : B[j];
- if (Aleft <= Bright && Bleft <= Aright) {
- return Math.max(Aleft, Bleft);
- } else if (Aleft > Bright) {
- right = i - 1;
- } else {
- left = i + 1;
- }
- }
- throw new IllegalArgumentException("Invalid input");
- }
- public static void main(String[] args) {
- int[] A = {1, 3, 5, 7, 9};
- int[] B = {2, 4, 6, 8, 10};
- int k = 3;
- int result = findKthLargest(A, B, k);
- System.out.println("The " + k + "rd largest element is: " + result);
- }
- }
复制代码 |
|