LeetCode OJ 4. Median of Two Sorted Arrays

时间:2021-12-29 17:02:25

There are two sorted arrays nums1 and nums2 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)).

Example 1:

nums1 = [1, 3]
nums2 = [2] The median is 2.0

Example 2:

nums1 = [1, 2]
nums2 = [3, 4] The median is (2 + 3)/2 = 2.5

Subscribe to see which companies asked this question


【题目分析】

给定两个升序排列的整数数组,找到这两个数组所有元素的中位数。


【思路】

LeetCode OJ 4. Median of Two Sorted ArraysLeetCode OJ 4. Median of Two Sorted ArraysLeetCode OJ 4. Median of Two Sorted ArraysLeetCode OJ 4. Median of Two Sorted ArraysLeetCode OJ 4. Median of Two Sorted ArraysLeetCode OJ 4. Median of Two Sorted Arrays


【java代码】

 public class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int[] A = nums1, B = nums2;
int m = nums1.length, n = nums2.length; if(m > n){
A = nums2; B = nums1;
m = nums2.length; n = nums1.length;
} if(n == 0) return 0; int mini = 0, maxi = m;
int i = 0, j = 0;
int maxofleft, minofright = 0; while(mini <= maxi){
i = (maxi - mini)/2 + mini;
j = (m + n + 1)/2 - i;
if(j > 0 && i < m && B[j-1] > A[i]){
mini = i + 1;
} //i is too small
else if(i > 0 && j < n && A[i-1] > B[j]){
maxi = i - 1;
} //i is too big
else{
if(i == 0) maxofleft = B[j-1];
else if(j == 0) maxofleft = A[i-1];
else maxofleft = Math.max(A[i-1], B[j-1]); if((m + n)%2 == 1) return maxofleft; if(i == m) minofright = B[j];
else if(j == n) minofright = A[i];
else minofright = Math.min(B[j], A[i]); return (double)(maxofleft + minofright) / 2.0;
}
}
return 0;
}
}