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
}
轉載于:https://www.cnblogs.com/longjin2018/p/9854418.html
總結
以上是生活随笔為你收集整理的Algs4-1.4.12找出两个有序数组的公共元素-方法1的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Bytomd 助记词恢复密钥体验指南
- 下一篇: 【3y】从零单排学Redis【青铜】