小算法 一個從四秒到10毫秒,花了1年的算法問題?

問題描述:html

有兩組隨機生成的(0~99999)Int32數據A和B,將A按順序判斷在B中是否存在並記錄在Boolean型的C中算法

 

 1 public static void main(String[] args)
 2     {
 3         //B數組:[5,2,4,1]
 4         
 5         Random rand = new Random();
 6         int maxValue = 120000;//假定A和B 的最大值
 7         int length = 70000;//a,b 的長度
 8         int [] a = new int[length];
 9         int [] b = new int[length];
10         boolean[] c= new boolean[length];
11         boolean[] temp = new boolean[maxValue];
12         //隨機初始化啊a,b數組
13         for(int i = 0;i<length;i++){
14             a[i] = rand.nextInt(maxValue);
15             b[i] = rand.nextInt(maxValue);
16         }
17         long t1 = System.currentTimeMillis();
18         //循環B,驗證元素是否存在(循環B,將B中值做爲a的下標,對應位置標記爲true)
19         for (int item : b) {
20             temp[item] = true;
21         }
22         
23         for(int i = 0;i<a.length;i++){
24             if(temp[a[i]])
25                 c[i] = true;
26         }
27         long t2 = System.currentTimeMillis();
28         System.out.println(t2-t1);
29     }

 

不算初始化,5毫秒左右數組

 

 

---dom

參考:post

一個從四秒到10毫秒,花了1年的算法問題?url

相關文章
相關標籤/搜索