数据结构-武大933

2018武汉大学933

两个整数递增有序序列 A,B 分别有 n 和 m 个元素,求第 k 大的数(1≤K≤n+m), 要求最佳时间空间复杂度。

函数原型:int kMax(int[] A,int[] B,int k)

例子:

输入

A[1,3,4,5,6]

B[3,4,5,6]

k=4

输出

4

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#define MAX 0x3f3f3f3f
using namespace std;

int findIthValue(int a[], int n1, int b[], int n2, int k)
{
	/*
		其实和归并的思想差不多,只是要在归并的过程中判断已经拍好了几个元素了而已
		要注意的是可能有一个数组提前被遍历完成的情况,其他的都很简单 
	*/
	int s1= 0, s2= 0;
	int count = 0, now = 0;
	while(s1 < n1 && s2 < n2)
	{
		if(a[s1] <= b[s2])
		{
			now = a[s1++];
			count++;
		}
		else if(a[s1] > b[s2])
		{
			now = b[s2++];
			count++;
		}
		if(count == k)
			return now;
	}

	while(s1 < n1)
	{
		now = a[s1++];
		count++;
		if(count == k)
			return now;
	}
	while(s2 < n2)
	{
		now = b[s2++];
		count++;
		if(count == k)
			return now;
	}
	
	return MAX;
}

int main()
{
	
	int a[] = {1};
	int b[] = {3,4,6,8};
	int result = findIthValue(a, 1, b, 4, 3);
	cout<<"THe result is:"<<result;
	return 0;
 } 

猜你喜欢

转载自blog.csdn.net/LiuKe369/article/details/81395830