leetcode 4 median of two sorted arrays
本文给出leetcode第四题Median of Two Sorted Arrays的答案及所用到的简单知识总结,适用于C++初学者
本文代码下载地址
目录
题目
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
插入法
#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
double median = 0;
int last_time = 0;
int this_time = 0;
vector<int> temp;
vector<int> canshu;
bool flag = nums1.size()>nums2.size()? 1:0;
if(flag){
temp = nums1;
canshu = nums2;
}
else{
temp = nums2;
canshu = nums1;
}
for(int i=0;i<canshu.size();i++){
this_time = findplace(temp, last_time, canshu[i]);
temp.insert(temp.begin()+this_time, canshu[i]);
last_time = this_time;
}
if((nums1.size() + nums2.size())%2 == 0)
median = ( 1.0* temp[(nums1.size() + nums2.size())/2] + 1.0* temp[(nums1.size() + nums2.size() - 1)/2] )/2;
else
median = temp[(nums1.size() + nums2.size())/2];
return median;
}
int findplace(vector<int>& temp, int last_time, int n){
int ans;
int begin = last_time;
int end = temp.size();
while(end-begin>1){
if(n>temp[(begin+end)/2])
begin = (int)(begin + end)/2;
else
end = (int)(begin + end)/2;
}
if(begin == end)
ans = n>temp[end]? end + 1: begin;
else{
if (n<temp[begin])
ans = begin;
else if (n>temp[end<temp.size()-1? end:temp.size()-1])
ans = end<temp.size()-1? end+1:temp.size();
else
ans = end<temp.size()-1? end:temp.size()-1;
}
return ans;
}
};
int main(){
Solution t;
int a[] = {1,2};
int b[] = {1,1};
vector<int> tempa;
vector<int> tempb;
for(int i=0;i<sizeof(a)/sizeof(int);i++){
tempa.push_back(a[i]);
}
for(int i=0;i<sizeof(b)/sizeof(int);i++){
tempb.push_back(b[i]);
}
double ans = t.findMedianSortedArrays(tempa,tempb);
cout<<ans<<endl;
system("pause");
return 0;
}
此题目我的思路如下:首先判断给出的两个数组的长短,将较短的数组中包含的元素一个一个地按二分法比较大小并插入较长的数组中。temp 为被插入数组, canshu 为插入数组,即我们需要将 canshu 中的每一位插入 temp 中,并在插入后更新 temp 。定义函数findplace,以被插入数组temp、被插入数组插入位置的起点和插入数字为参数,以插入位置为返回值。因为两个数组都已经是从大到小排列的了,所以我们在已知 canshu[i] 插入位置为 a 的情况下, canshu[i+1] 的插入位置一定会大于 a ,即我们只需要在 a 之后对 canshu[i+1] 进行查找和比较。
程序中有一些较小的值得注意的点,如在函数findplace中的语句
if(begin == end)
ans = n>temp[end]? end + 1: begin;
else{
if (n<temp[begin])
ans = begin;
else if (n>temp[end<temp.size()-1? end:temp.size()-1])
ans = end<temp.size()-1? end+1:temp.size();
else
ans = end<temp.size()-1? end:temp.size()-1;
}
返回值 ans 需要特别注意,否则会越界。
本代码提交后运行速度在后24%。