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)).
思路O(logx)的算法,就想到二分法。二分法结束的条件是任何一个array只剩下一个元素了。每次递归(二分),去除某个array的一半。另外注意,每次二分至少要去掉一个元素。
class Solution { public: double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { int size1 = nums1.size(); int size2 = nums2.size(); int size = size1 + size2; int m = size >> 1; if(nums1.empty()){ if(size%2 == 1) return nums2[m]; else return (double) (nums2[m-1] + nums2[m])/2; } if(nums2.empty()){ if(size%2 == 1) return nums1[m]; else return (double) (nums1[m-1] + nums1[m])/2; } if(size%2 == 1) return findK(nums1, nums2, 0, size1-1, 0, size2-1, m); else return (double)(findK(nums1, nums2, 0, size1-1, 0, size2-1, m-1)+findK(nums1, nums2, 0, size1-1, 0, size2-1, m))/2; } int findK(vector<int>& nums1, vector<int>& nums2,int s1, int e1, int s2, int e2, int k){ if(s1 == e1){ if(k == 0) return min(nums1[s1],nums2[s2]); //为了防止s2+k-1越界 if(nums1[s1] < nums2[s2+k-1]) return nums2[s2+k-1]; else if(s2+k-1 == e2) return nums1[s1]; //为了防止s2+k越界 else return min(nums1[s1], nums2[s2+k]); } if(s2 == e2){ if(k == 0) return min(nums1[s1],nums2[s2]); //为了防止s1+k-1越界 if(nums2[s2] < nums1[s1+k]) return max(nums2[s2],nums1[s1+k-1]); else if(s1+k-1 == e1) return nums2[s2]; //为了防止s1+k越界 else return min(nums2[s2], nums1[s1+k]); } int m1 = (s1+e1)>>1; int m2 = (s2+e2)>>1; int halfLen = (e1 - s1 + e2 - s2 + 2) >> 1; if(k >= halfLen){ //k is in the second half if(nums1[m1] < nums2[m2]){ //delete first half of num1 return findK(nums1, nums2, m1+1, e1, s2, e2, k-(m1-s1+1)); //+1是考虑到m1==s1的情况,每次二分至少要去除一个元素 } else{ //delete fist half of num2 return findK(nums1, nums2, s1, e1, m2+1, e2, k-(m2-s2+1));//+1是考虑到m2==s2的情况,每次二分至少要去除一个元素 } } else{ //k is in the first half if(nums1[m1] < nums2[m2]){ //delete second half of num2 return findK(nums1, nums2, s1, e1, s2, m2, k); } else{ //delete second half of num1 return findK(nums1, nums2, s1, m1, s2, e2, k); } } } };
时间: 2024-10-27 11:13:10