您的位置:首页 > 其它

LeetCode 4. Median of Two Sorted Arrays

2018-03-12 22:22 471 查看
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

给出两个排好序的数列,求中位数。设计一个函数用来取最小值即可很方便得到

class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int n1=nums1.size();
int n2=nums2.size();
if(n1==0&&n2==0)return 0.0;
int p1=0,p2=0;
double ans=0.0;
int half=(n1+n2-1)/2;
int i;
for(i=0;i<half;i++){
ans=getmin(nums1,nums2,&p1,&p2);
}
ans=getmin(nums1,nums2,&p1,&p2);
if((n1+n2)%2==0){
ans+=getmin(nums1,nums2,&p1,&p2);

4000
ans=ans/2.0;
}
return ans;
}
double getmin(vector<int>&v1,vector<int>&v2,int *p1,int *p2){
int n1=v1.size();
int n2=v2.size();
if(n1==*p1){
double ans=(double)v2[*p2];
(*p2)++;
return ans;
}
if(n2==*p2){
double ans=(double)v1[*p1];
(*p1)++;
return ans;
}
double ans;
if(v1[*p1]<v2[*p2]){
ans=v1[*p1];
(*p1)++;
return ans;
}
else{
ans=v2[*p2];
(*p2)++;
return ans;
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: