2015-02-12 58 views
0

基本上我必須返回一個數組中重複的n個數組到另一個長度爲m的數組。 到目前爲止我的代碼:返回n個數字的數組重複到另一個數組中

public class Histogram { 
    public static int[] frequency(int[] a, int M) { 
     int[] m = new int[M]; 
     int count = 0; 
     for(int j = 0; j < a.length; j++) 
     for(int i = 0; i < m.length; i++) 
      if(i == a[j]){ 
       m[i] = count++; 
      } 
     } 
     return m; 
} public static void main(String[] args) { 
    int[] a = {7, 4, 9, 1, 10, 11, 11, 1, 5, 8, 4, 2, 9, 4, 3, 9, 
       2, 10, 11, 7, 7, 1, 11, 3, 8, 8, 10, 4, 10, 5}; 
    int[] b = frequency(a, 12); 
    for (int i = 0; i < b.length; i++) { 
     Std.Out.println(i + "->" + b[i]); 
    } } } 

這是輸出IM應該得到

0->0 
1->3 
2->2 
3->2 
4->4 
5->2 
6->0 
7->3 
8->3 
9->3 
10->4 
11->4 

但即時得到

0->0 
1->21 
2->16 
3->23 
4->27 
5->29 
6->0 
7->20 
8->25 
9->15 
10->28 
11->22 

我到底做錯了什麼?

回答

0

我不會給你一個不同的解決方案,而是要顯示你的代碼中的錯誤。如果我們按照代碼中的邏輯進行操作,則會出現一些錯誤:

1)第一次循環後應將count重置爲0。否則,您將總結先前迭代的計數。

2)count ++應該在賦值之前,否則會先賦值然後遞增。或者你可以使用++計數。

3)第一個循環應該結束。

public static int[] frequency(int[] a, int M) { 
    int[] m = new int[M]; 
    int count; 
    for(int i = 0; i < m.length; i++) { 
    count =0; 
    for(int j = 0; j < a.length; j++) 
     if(i == a[j]){ 
      count++; 
      m[i] = count; 
     } 
    } 

    return m; 

    } 

問候。

+0

非常感謝您指出我的錯誤,這讓我看到我錯過的更有意義,而不是僅僅接受別人的代碼。無論如何,我會upvote你,但我從字面上只是一個帳戶,並仍然相當新的編碼。再一次,謝謝! – WallyWest 2015-02-12 02:41:27

0

這應該解決它並做好工作!

public class Histogram { 

    public static int[] frequency(int[] a, int M) { 
     int[] m = new int[M]; 
     for(int j = 0; j < a.length; j++) { 
      m[a[j]] += 1; 
     } 
     return m; 
    } 

    public static void main(String[] args) { 
     int[] a = {7, 4, 9, 1, 10, 11, 11, 1, 5, 8, 4, 2, 9, 4, 3, 9, 
       2, 10, 11, 7, 7, 1, 11, 3, 8, 8, 10, 4, 10, 5}; 
     int[] b = frequency(a, 12); 
     for (int i = 0; i < b.length; i++) { 
      System.out.println(i + "->" + b[i]); 
     } 
    } 
} 
0
public class Histogram { 
    public static int[] frequency(int[] a, int M) { 
     int[] m = new int[M]; 
     for(int i = 0; i < a.length; i++) //loop through a 
      if(i < M) //number check 
       m[a[i]]++; //add one to m at index a[i] 
     return m;  
     } 
} 

這是該方法的頻率正確的代碼,還檢查該號碼是否在範圍內。

相關問題