求两个有序数组A和B的第k大的数——Java

package com.bupt;

public class Solution6 {
	
	public static int Search(int[] a,int startA,int endA,int[] b,int startB,int endB,int k){
		if(k ==1){
			if(a[startA]>b[startB]){
				return b[startB];
			}else{
				return a[startA];
			}
		}
		if(startA>endA){
			return b[startB+k-1];
		}
		if(startB>endB){
			return a[startA+k-1];
		}
		int countA = 0;							//分别取A,B数组中元素的个数
		int countB = 0;
		if(a.length<b.length){					//查看k/2是否大于数组A或B的长度,并进行相应的处理
			if(endA-startA+1>k/2){
				countA = k/2;
			}else{
				countA = endA-startA+1;
			}
			countB = k-countA;
		}else{
			if(endB-startB+1>k/2){
				countB = k/2;
			}else{
				countB = endB-startB+1;
			}
			countA = k-countB;
		}
		
		int indexA = startA+countA-1;			//A和B的比较点
		int indexB = startB+countB-1;
		if(a[indexA] == b[indexB]){
			return a[indexA];
		}else{
			if(a[indexA]>b[indexB]){			//根据比较的结果进行相应递归
				return Search(a,startA,indexA,b,indexB+1,endB,k-countB);
			}else{
				return Search(a,indexA+1,endA,b,startB,indexB,k-countA);
			}
		}
	}

    public static void main(String[] args){
    	int[] a = new int[]{1,9,10,18};
        int[] b = new int[]{7,10};
        int k = 6;
        System.out.println(Search(a,0,a.length-1,b,0,b.length-1,k));
    }
    
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值