Algorithm 04 : 寻找两个有序数组中的第N个数,要求时间复杂度为O(logm+logn)

Question : Give a divide and conquer algorithm for the following problem : you are
given two sorted lists of size m and n, and are allowed unit time access
to the ith element of each list. Given an O(logm+logn) time algorithm for
computing the kth largest element in the union of the two lists.
(For simplicity, you can assume that the elements of the two lists are
distinct).

问题:寻找两个有序数组中的第N个数,要求时间复杂度为O(logm+logn)。




/**
* @author YuHuang
* @vision 2011-10-04
* This program is only for algorithm training.
*
*/

import java.lang.RuntimeException;

public class SearchKthNumber {

private int[] aArray;
private int[] bArray;

public SearchKthNumber(int[] aArray,int[] bArray){
this.aArray=aArray;
this.bArray=bArray;
if(this.aArray==null||this.bArray==null){
throw new RuntimeException("Array should not be null!");
}
}

public int doSearch(int aLeft,int aRight,int bLeft,int bRight,int k){
int aMiddle = (aLeft+aRight)/2;
int bMiddle = (bLeft+bRight)/2;

if(aLeft>aRight){
return bArray[bLeft+k-1];
}

if(bLeft>bRight){
return aArray[aLeft+k-1];
}

if(aArray[aMiddle]>bArray[bMiddle]){
if(k<=(aMiddle-aLeft)+(bMiddle-bLeft)+1){
return doSearch(aLeft,aMiddle-1,bLeft,bRight,k);
}else{
return doSearch(aLeft,aRight,bMiddle+1,bRight,k-(bMiddle-bLeft)-1);
}
}else{
if(k<=((aMiddle-aLeft)+(bMiddle-bLeft)+1)){
return doSearch(aLeft,aRight,bLeft,bMiddle-1,k);
}else{
return doSearch(aMiddle+1,aRight,bLeft,bRight,k-(aMiddle-aLeft)-1);
}
}
}


public static void main(String[] args){
int[] aArray=new int[]{1,3,5,6,8,9,11,18,20};
int[] bArray=new int[]{2,4,7,16,22,29,39,40,55,100};

SearchKthNumber sn=new SearchKthNumber(aArray,bArray);
int k=2;
int result=sn.doSearch(0,aArray.length-1,0,bArray.length-1,k);
System.out.println("The "+k+"th"+" Number : "+result);
}

}





[color=blue]欢迎提出更优化的解决方案,谢谢![/color]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值