LeetCode4 兩個排序陣列的中位數
阿新 • • 發佈:2018-12-13
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)).
You may assume nums1 and nums2 cannot be both empty.
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
public double findMedianSortedArrays(int[] nums1, int[] nums2) { int n = nums1.length; int m = nums2.length; int left = (n + m + 1) / 2; int right = (n + m + 2) / 2; return 0.5 * (getKth(nums1, 0, n-1, nums2, 0, m-1, left) + getKth(nums1, 0, n-1, nums2, 0, m-1, right)); } private double getKth(int[] nums1, int start1, int end1, int[] nums2, int start2, int end2, int k){ int len1 = end1 - start1 + 1; int len2 = end2 - start2 + 1; if(len1 > len2){ return getKth(nums2,start2,end2,nums1,start1,end1,k); } if(len1 == 0) return nums2[start2 + k - 1]; if(k == 1) return Math.min(nums1[start1],nums2[start2]); int s1 = Math.min(start1 + k/2 - 1, start1 + len1 - 1); int s2 = Math.min(start2 + k/2 - 1, start2 + len2 - 1); if(nums1[s1] < nums2[s2]){ return getKth(nums1,s1+1,end1,nums2,start2,end2,k-Math.min(k/2,len1)); }else{ return getKth(nums1,start1,end1,nums2,s2+1,end2,k-Math.min(k/2,len2)); } }