2014-02-21 58 views
0

我曾嘗試下面的程序,我堅持請協助me.Below是我的程序如何查找重複/重複數組值並將其顯示在輸出中?

import java.util.ArrayList; 

public class PrintNosandRepetition 

{ 

public static void main(String[] args) 

{ 

int a[] = new int[] {1,3,4,5,6,3,2,4,6,7,9,4,12,3,4,6,8,9,7,6,43,2,4,7,7,5,2,1,3,4,6,311,1}; 

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

    System.out.print(a[i]+ " "); 

    } 
    for (i=1, j<a.length; j++) 


    } 

輸出必須是時尚「1重複3次」 .etc

+1

如果您規範化數據集,例如先排序吧 – Madbreaks

回答

2

你可以對原始數組進行排序,然後遍歷它以逐個掃描元素。這將運行在O(nlogn)

或者你可以使用一個Map<Integer, Integer>它將存儲每個數字的出現次數。此解決方案在O(n)中運行,但使用額外的內存。

1
int a[] = new int[] {1,3,4,5,6,3,2,4,6,7,9,4,12,3,4,6,8,9,7,6,43,2,4,7,7,5,2,1,3,4,6,311,1}; 

HashMap occurrenceMap = new HashMap()<Integer, Integer>; 
int number; 
Integer occurrences; //accepts null 

for (int i=0; i<a.length; i++){ 
    number = a[i]; 
    occurrences = occurrenceMap.get(number); 
    if (occurrences == null) { //had no occurrences until this point 
     occurrenceMap.put(number, 1); 
    } 
    else { 
     occurrenceMap.put(number, occurrences+1); 
    } 
} 

//iterate over your map and print the pairs 

現在無法對其進行測試,因此對於任何最終的語法錯誤表示抱歉。

+0

這是什麼HashMap?它有什麼作用 ?另外爲什麼我們使用這個「」? – user3220565

+0

它將一些對象(Key)映射到另一個對象(Value)。創建一個新的HashMap()意味着它將把整數(它們是你數組的元素)映射到其他整數(它們各自的出現次數)。你可以在這裏找到一個很好的例子:http://www.tutorialspoint.com/java/java_hashmap_class.htm – lucasnadalutti