数据结构-武大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;
 } 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值