由于排序结果不需要返回,所以这里用temp1,2记录中间两个决定中位数即可
class Solution {
public:
double findmid(vector<int>& nums){
int n=nums.size();
if(n%2==1)return (double)nums[n/2];
else return ((double)nums[n/2-1]+(double)nums[n/2])/2;
}
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
if(nums1.empty()&&nums2.empty())return 0.0;
if(nums1.empty()) return findmid(nums2);
if(nums2.empty()) return findmid(nums1);
int n1=nums1.size();
int n2=nums2.size();
int temp1=0,temp2=0;
int i=0,j=0,k=0;
while(k<=(n1+n2)/2){
temp1=temp2;
k++;
if(i<n1&&j<n2){
if(nums1[i]<nums2[j]){
temp2=nums1[i];
i++;
}else{
temp2=nums2[j];
j++;
}
}else if(i<n1){
temp2=nums1[i];
i++;
}
else{
temp2=nums2[j];
j++;
}
}
if((n1+n2)%2==1)return temp2;
return ((double)temp1+(double)temp2)/2;
}
};
暴力解
class Solution {
public:
double findmid(vector<int>& nums){
int n=nums.size();
if(n%2==1)return (double)nums[n/2];
else return ((double)nums[n/2-1]+(double)nums[n/2])/2;
}
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
if(nums1.empty()&&nums2.empty())return 0.0;
if(nums1.empty()) return findmid(nums2);
if(nums2.empty()) return findmid(nums1);
int n=nums2.size();
for(int i:nums2)nums1.emplace_back(i);
sort(nums1.begin(),nums1.end());
return findmid(nums1);
}
};
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)