首页 > 解决方案 > 如何获取此列表以打印数组中的重复值而不打印两次值

问题描述

 public static void printOrganizedList(int[] array) {
    int[] temp = array;
    System.out.println("N        Count");

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

        for (int j = 0; j < array.length; j++) {
            if(array[i] == array[j]) {
                count++;
            }
        }
        for(int n = i-1; n > 0; n--) {
            if(array[n] == array[i]) {
                break;
            }
            else {
                System.out.println(array[i] + "        " + count);
            }
        }
    }
}

此方法用于接收一个数组并打印重复值以及它在数组中出现的次数。像这样:

     -12, 3, -12, 4, 1, 1, -12, 1, 1, 2, 3, 4, 2, 3, -12

    The program output should be:

    N        Count

    4               2

    3               3

    2               2

    1               4

    -1             1

    -12          4

我的问题是,无论我尝试什么,该方法总是吐出重复的数字及其重复次数,重复次数与重复次数一样多。所以而不是输出

    "-12        4"

它将输出:

    "-12        4"
    "-12        4"
    "-12        4"
    "-12        4"

我也知道有更先进和更有效的技术,但我们还没有学到很多东西。提前致谢。

标签: javaarraysloops

解决方案


这可以使用 HashMap 轻松实现。您可以创建一个 Hashmap,它将元素保存为键并将出现次数保留为值。

public static void printOrganizedList(int[] array) {
    System.out.println("N        Count");

    HashMap<Integer, Integer> countMap = new HashMap<>();

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

        if (countMap.containsKey(array[i])){
            int count = countMap.get(array[i]);
            countMap.replace(array[i], count + 1);
        }else{
            countMap.put(array[i], 1);
        }
    }

    Iterator iterator = countMap.entrySet().iterator();
    while (iterator.hasNext()){
        Map.Entry mapElement = (Map.Entry) iterator.next();
        int key = (int) mapElement.getKey();
        int count = (int) mapElement.getValue();
        System.out.println(key + "        " + count);
    }
}

此外,您编写的程序的时间复杂度达到 O(N^2),这对于大型程序来说可能是一个非常大的瓶颈。

上面带有 hashmap 实现的程序只会花费你 O(N)


推荐阅读