2016-01-05 20 views
-6

我在學習java,當我需要爲數組中的每個數字查找顯示數時,我有一個練習,數字是0-100,這需要在O (N)。現在,我不知道如何做到這一點,所以我看到了解決方案,並沒有真正瞭解它,該解決方案的解釋是非常差,這裏的代碼:瞭解我的作業中的一些代碼

public static void count (int [] data){ 
    final int N = 100; 
    int [] temp = new int[N]; 
    int i; 
    for (i=0; i < data.length; i++){ 
     temp[data[i]]+=1; 
    } 
    for (i=0; i < N; i++){ 
     if (temp[i] != 0) 
      System.out.println(i + ":" +temp[i]); 
    } 

} 

我特意沒拿到線

temp[data[i]]+=1; 

如果有人可以解釋我的每行代碼, 的想法,我真的很感激任何幫助。謝謝!

+3

是什麼解釋?你從中不瞭解什麼? –

回答

0

基本上,該代碼是這樣做的: 1)用100個位置(全部設置爲0)初始化臨時數組; 2)迭代數據數組並相對於它正在處理的數據數組值的索引增加值。就拿這個例子:

int[] data = {23,11,10,23,5}; 

temp[data[0]] += 1 
temp[23] += 1 
temp[23] = temp[23] + 1 = 0 + 1 = 1 

temp[data[1]] += 1 
temp[11] += 1 
temp[11] = temp[11] + 1 = 0 + 1 = 1 

temp[data[2]] += 1 
temp[10] += 1 
temp[10] = temp[10] + 1 = 0 + 1 = 1 

temp[data[3]] += 1 
temp[23] += 1 
temp[23] = temp[23] + 1 = 1 + 1 = 2 

temp[data[4]] += 1 
temp[5] += 1 
temp[5] = temp[5] + 1 = 0 + 1 = 1 

因此,在這種情況下,你會而其他的只出現一次注意到值23出現數據陣列中的兩次。這樣,您可以計算O(n)中的出現次數,即僅對數組進行一次遍歷。

+0

有意義。謝謝! – Avishay28

0
/* method signature 
static - method can be used without instantiation of the class 
public - can be accessed by other classes 
void - the return of the function count. 
int [] data - parameter of the function. This function receives an array of int 
*/ 

public static void count (int [] data){ 
    final int N = 100; 
    int [] temp = new int[N]; 
    int i; 

//for i = 0 until i < size of the array passed as parameter, increment 1 in i 

    for (i=0; i < data.length; i++){ 

/* 
each iteration of this for increments 1 in the array temp at the position informed by the value of parameter data in position i. 
caution: this can bring serious problems of segmentation fault, in other words, you can try to store in a position of the array temp that doesn't exist. 
This will happen because you cannot guarantee the number that will be store in data[i]. If data[i] > 99 (because N = 100), you will face a segmentation fault. 
*/ 

     temp[data[i]]+=1; 
    } 

//here you will print the value stored at temp array in position i. From 0 to 99 

    for (i=0; i < N; i++) 
    { 
      if (temp[i] != 0) 
       System.out.println(i + ":" +temp[i]); 
    } 

} 

HOPE IT HELPS. 

You need to study more. Your question is so naive.