Coursera Algorithms week3 快速排序 练习测验: Selection in two sorted arrays(从两个有序数组中寻找第K大元素)

时间:2023-12-05 15:05:08

题目原文

Selection in two sorted arrays. Given two sorted arrays a[] and b[], of sizes n1 and n2, respectively, design an algorithm to find the kth largest key. The order  of growth of the worst case running time of your algorithm should be logn, where n = n1 + n2.

Version 1 : n1 = n2 and k = n/2

Version 2: k = n/2

Version 3: no restrictions

分析:

这个题目是要求从两个有序数组中寻找第K大元素,直观解法就是把连个数组归并排序,这样时间复杂度就是O(n),但是题目只要求知道第K大元素,其余比K大的元素的排列顺序并不关心。

默认数组a和数组b都是从小到大排序的。不论第K大元素在a或b中,其右侧元素一定大于K,可考虑分别从a和b中排除右侧(k-1)/2个元素,剩下的就是在未排除区间寻找第(k-已排除元素)大元素。通过递归逐步缩小比较范围。具体算法见如下代码。

 package week3;

 import java.util.Arrays;
import edu.princeton.cs.algs4.StdRandom; public class KthInTwoSortedArrays {
/**
* 寻找第K大元素
* @param a 数组a
* @param alo a的查找区间下界
* @param ahi a的查找区间上界
* @param b 数组b
* @param blo b的查找区间下界
* @param bhi b的查找区间上界
* @param k 当前查找区间的第k大元素
* @return
*/
private static int find(int[] a, int alo, int ahi,int[] b, int blo, int bhi, int k){
if(alo > ahi) return b[bhi-k+1];
if(blo > bhi) return a[ahi-k+1];
if(k==1) return a[ahi] > b[bhi]? a[ahi]:b[bhi];
//直接用bhi-(k-1)/2或ahi-(k-1)/2进行查找可能会将第K个元素给漏掉
int bt = bhi-(k-1)/2 > blo ? bhi-(k-1)/2:blo;
int at = ahi-(k-1)/2 > alo ? ahi-(k-1)/2:alo;
if(a[at] >= b[bt])
return find(a,alo,at-1,b,blo,bhi,k-(ahi-at+1));
else
return find(a,alo,ahi,b,blo,bt-1,k-(bhi-bt+1));
} public static void main(String[] args){
int n = 10;
int n1 = StdRandom.uniform(n);
int n2 = n-n1;
int[] a = new int[n1];
int[] b = new int[n2];
for(int i=0;i<n1;i++){
a[i] = StdRandom.uniform(100);
}
for(int i=0;i<n2;i++){
b[i] = StdRandom.uniform(100);
}
Arrays.sort(a);
Arrays.sort(b);
System.out.println("a="+Arrays.toString(a));
System.out.println("b="+Arrays.toString(b));
int[] c = new int[n];
int i = 0;
int j = 0;
int l = 0;
while(l<n){
if(i>=n1) c[l++] = b[j++];
else if(j>=n2) c[l++] = a[i++];
else{
if(a[i] <= b[j])
c[l++] = a[i++];
else
c[l++] = b[j++];
} }
System.out.println("c="+Arrays.toString(c)); int k =StdRandom.uniform(1,n);
int largestK = find(a,0,n1-1,b,0,n2-1,k);
System.out.println("第"+k+"大元素是:"+largestK);
}
}