标签:turn leetcode size 复杂 example ems max empty res
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
题解:
查找中位数要利用二分查找才能符合题目要求的时间复杂度
class Solution { public: double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { int len1=nums1.size(); int len2=nums2.size(); if(len1>len2) return findMedianSortedArrays(nums2,nums1); int low=0,heigh=len1*2; int lMax1=0,rMin1=0,lMax2=0,rMin2=0; while(low<=heigh) { int c1=(low+heigh)>>1; int c2=len1+len2-c1; lMax1=(c1==0)?INT_MIN:nums1[(c1-1)/2]; rMin1=(c1==2*len1)?INT_MAX:nums1[c1/2]; lMax2=(c2==0)?INT_MIN:nums2[(c2-1)/2]; rMin2=(c2==2*len2)?INT_MAX:nums2[c2/2]; if(lMax1>rMin2) heigh=c1-1; else if(lMax2>rMin1) low=c1+1; else break; } return (max(lMax1,lMax2)+min(rMin1,rMin2))/2.0; } };
标签:turn leetcode size 复杂 example ems max empty res
原文地址:https://www.cnblogs.com/tianzeng/p/11462443.html