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.0Example 2:
nums1 = [1, 2] nums2 = [3, 4] The median is (2 + 3)/2 = 2.5寻找两个有序数组的中位数
public class Solution { public double findMedianSortedArrays(int[] nums1, int[] nums2) { int m = nums1.length; int n = nums2.length; int i=0,j=0,k = 0; int a=0,b=0; while (k <= (m+n)/2) { if (i < m && j < n) { a = b; b = nums1[i] < nums2[j] ? nums1[i++] : nums2[j++]; } else if (i < m) { a = b; b = nums1[i++]; } else if (j < n) { a = b; b = nums2[j++]; } k++; } if ((m+n)%2 == 1) { return (double) b; } else { return ((double)a + (double)b)/2; } } }