leetcode练习4(求两个正序数组中位数)

题目:给定两个大小为 m 和 n 的正序(从小到大数组 nums1 和 nums2,请你找出这两个正序数组的中位数
你可以假设 nums1 和 nums2 不会同时为空。

题解(1):如果要求时间复杂度为O(log(m+n)),可以想到的就是二分法。(时间复杂度:O(log(m+n))

class solution
{
private:
	vector<int>m;
	vector<int>n;
public:
	solution(vector<int>a,vector<int>b) {
		 m=a;
		n=b;
	}
	    double find() {
		vector<int>a;
		vector<int>b;
        a = (m.size()<n.size())?m:n;
		b = (m.size()<n.size())?n:m;
		int res=(a.size()+b.size())/2;
		int mid = 0;
		int starta = 0, startb = 0;       //向中位数处逐步靠近的指针
		int end =((a.size() + b.size())%2==1)?0:1;
		
			while (res>0)
		{
			mid = res / 2 - 1;
			if (a.size() < mid + 1)      //防止容器越界
			{
				while (a.size() < mid + 1) {
					static int i = 0;
					a.push_back(b.size() - 1-(mid+1-a.size())+i);
					i++;
				}
			}
			if (mid < 0)
			{
				mid = 0;
			}
			while (a.size() < mid + starta + 1)
			{
				a.push_back(b[b.size() - 1]);
			}
			if (a[mid+starta] > b[mid+startb])           //防止容器越界
			{
				startb = startb+mid + 1;
			
			}
			else
			{
				starta = starta+mid + 1;
				if (starta + 1 > a.size())              //防止容器越界
				{
					a.push_back(b[b.size() - 1]);
				}
			}
			res = res -mid-1;
		}
		if (end == 0)                                 //若数组中的总元素个数为奇数,返回中间数
		{ 
			return min(a[starta], b[startb]);
		}
		if (end == 1)                                  //若数组的总元素个数为偶数,返回中间两数的平均值
		{
			
			
			return  (double)((double)(max(a[starta - 1], b[startb - 1]) + (double)min(a[starta], b[startb])) / 2);
			
		}

		
		
	}
};

题解(2):类似于窗口滑动,设置一个指针m指向较长数组a的第k个数(中位数的位置),设置另一个指针n指向较短数组b的开头(b[0]之前),进行比较,若a[m]>=b[n+1],则指针m向前移动一个位置,n向后移动一个位置,以此来逼近中位数。(时间复杂度:O(n))

class solution
{
private:
	vector<int>m;
	vector<int>n;
public:
	solution(vector<int>a,vector<int>b) {
		 m=a;
		 n=b;
	}
	    double find() {
	
		vector<int>a;
		vector<int>b;
        a = (m.size()<n.size())?m:n;
		b = (m.size()<n.size())?n:m;
		
		int mid = (a.size() + b.size()) /2 ;
		int endb = mid;
		int enda = -1;
		if (a.size() == b.size())       //让数组a、b长度不相等,防止越界现象出现
		{
			b.push_back(a[a.size()-1]);
			sort(b.begin(), b.end());
			a.erase(remove(a.begin(),a.end(), a[a.size() - 1]),a.end());

		
		}
		while (enda+1 < a.size()&&endb>-1)    
		{
		
			if (a[enda + 1] <= b[endb])
			{
				enda +=1;
				endb -= 1;
			}
			else { break; }
		}
		if ((a.size() + b.size()) % 2 == 1)
		{
			if (endb < 0) { return a[enda]; }
			return b[endb];
		}
		else {
			
			if (endb < 0) { return (double)(((double)a[enda] + (double)a[enda + 1]) / 2); }
			if (endb == 0) { (double)(((double)b[endb] + (double) a[enda]) / 2); }
			 return (double)(((double)b[endb] + (double)max(b[endb -1], a[enda])) / 2);
		}
	}
};

你可能感兴趣的:(leetcode练习4(求两个正序数组中位数))