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;
}
}
};
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;
}
}
};
相关文章推荐
- leetcode-4Median of Two Sorted Arrays
- LeetCode-4-Median of Two Sorted Arrays(C语言实现)
- Median of Two Sorted Arrays - LeetCode
- leetcode MEDIAN OF TWO SORTED ARRAYS
- leetcode.array--4. Median of Two Sorted Arrays
- [leetcode] Median of Two Sorted Arrays 两个排序数组找出第k个数,或者中位数
- 25th Feb: LeetCode 4 Median of Two Sorted Arrays
- LeetCode:Median of Two Sorted arrays
- Leetcode_Median of Two Sorted Arrays
- [LeetCode] Median of Two Sorted Arrays
- LeetCode 4. Median of Two Sorted Arrays
- LeetCode --- Median of Two Sorted Arrays
- [LeetCode]Median of Two Sorted Arrays
- leetcode 4. Median of Two Sorted Arrays
- Leetcode 4 Median of Two Sorted Arrays
- 4.Median of Two Sorted Arrays Leetcode Python
- [LeetCode]Median of Two Sorted Arrays
- leetcode 之Median of Two Sorted Arrays(五)
- LeetCode第四题(Median of Two Sorted Arrays)
- LeetCode-4:Median of Two Sorted Arrays