如何找到重复/重复的数组值并在输出中显示它们?

时间:2014-02-21 20:33:49

标签: java arrays

我已经尝试了下面的程序而且我被卡住请帮助我。我的程序是

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

2 个答案:

答案 0 :(得分:2)

您可以对原始数组进行排序,然后循环遍历它以逐个扫描元素。这将在O(nlogn)

中运行

或者您可以使用Map<Integer, Integer>来存储每个数字的出现次数。此解决方案在O(n)中运行,但使用额外的内存。

答案 1 :(得分: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

目前无法测试,所以我为任何最终的语法错误道歉。