Algs4-1.4.12找出两个有序数组的公共元素-方法1
1.4.12编写一个程序,有序打印给定的两个有序数组(含有N个int值)中的所有公共元素,程序在最坏情况下所需的运行时间应该和N成比。
答:
import java.util.Arrays;
public class TheSameElement
{
public static void main(String[] args)
{
int[] a1=In.readInts(args[0]);
int[] a2=In.readInts(args[1]);
Arrays.sort(a1);
Arrays.sort(a2);
int a1lo=0;
int a2lo=0;
int a2KeyIndex=0;
while (a1lo<a1.length && a2lo<a2.length)
{
a1lo=rankMax(a1,a1lo,a1.length-1,a1[a1lo]);
a2KeyIndex=rankMax(a2,a2lo,a2.length-1,a1[a1lo]);
if(a2KeyIndex!=-1)
{
StdOut.println(a1[a1lo]);
a2lo=a2KeyIndex+1;
}
a1lo++;
}
}
private static int rankMax(int[] a,int lo,int hi,int key)
{
int keyIndex=-1;
while(lo<=hi)
{
int mid=lo+(hi-lo)/2;
if (key<a[mid]) hi=mid-1;
else if(key>a[mid]) lo=hi+1;
else
{
keyIndex=mid;
lo=mid+1;
}//end if
}//end while
return keyIndex;
}//end rankMax
}