当前位置: 代码迷 >> 综合 >> Leetcode-Median of Two Sorted Arrays 时间复杂度O(M+N)
  详细解决方案

Leetcode-Median of Two Sorted Arrays 时间复杂度O(M+N)

热度:93   发布时间:2023-12-17 05:36:40.0
public class Solution {
    public double findMedianSortedArrays(int A[], int B[]) {
       int m = A.length, n = B.length;
boolean even = (m + n) % 2 == 0;
int median = (m + n) / 2;
int[] C = median==0?m==0?B:A:new int[median + 1];
int k = 0, i = 0, j = 0;
for (; i < A.length && j < B.length;) {
if (A[i] < B[j]) {
C[k++] = A[i++];
if (k-1 == median)
break;
} else if (B[j] < A[i]) {
C[k++] = B[j++];
if (k-1 == median)
break;
} else {
C[k++] = A[i++];
if (k-1 == median)
break;
C[k++] = B[j++];
if (k-1 == median)
break;
}
}
while (i < A.length && k<C.length) {
C[k++] = A[i++];
if (k-1 == median)
break;
}
while (j < B.length && k<C.length) {
C[k++] = B[j++];
if (k-1 == median)
break;
}


if (even) {
return (double) (C[median] + C[median - 1]) / 2.0;
}
return (double) C[median];
}

}

=====================

There are two sorted arrays A and B of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).

  相关解决方案