简体   繁体   English

确定每个整数出现在输入(数组)中的次数

[英]determining how many times each integer appears in the input (array)

it keeps repeating regardless of whether it's been already calculated or not. 无论是否已经计算,它都会不断重复。 You can see the example output. 您可以看到示例输出。 it already calculated the occurrence of 1, but when it sees 1 again, it will calculate it again! 它已经计算出1的出现,但是当再次看到1时,它将再次计算它!

public class SortingInLinearTime {
    public static int[][] howMany(int[] n){

        // Makes a double array list where the second value is occurrence of the first value.
        int[][] a = new int[n.length][2]; 
        int counter = 0;

        for(int i = 0; i != n.length; i++){
            for(int j = 0; j != n.length; j++) {

                if(n[i] == n[j]){
                    counter++;
                }
            }
            a[i][0] = n[i];
            a[i][1] = counter;
            counter = 0;
        }

        // printer helper function
        for(int i = 0; i != n.length; i++){ 
            System.out.print(a[i][0] + " occurs ");
            System.out.println(a[i][1] + " times");
        }
        return a;
    }

    public static void main(String[] args) {
        int[] testArray = {1, 2, 3, 1, 2, 3, 4};
        System.out.print(howMany(testArray));
    }
}

output: 1 occurs 2 times 2 occurs 2 times 3 occurs 2 times 1 occurs 2 times 2 occurs 2 times 3 occurs 2 times 4 occurs 1 times [[I@15db9742 输出:1次发生2次2次发生2次3次发生2次1次发生2次2次发生2次3次发生2次4次发生1次[[I @ 15db9742

In the first loop with i, you are recounting the same values again and again. 在与i的第一个循环中,您一次又一次地重新计算相同的值。 1 appears when i = 0 and when i = 3 as well. 当i = 0以及i = 3时,也会出现1。 you once counted for 1 when i == 0 and recounted again at i == 3 in array n. 您曾经在i == 0时计数为1,然后在数组n中的i == 3处再次计数。 However, I believe the best solution for your problem could be achieved by changing your data structure from int[][] to an hashmap. 但是,我相信将数据结构从int [] []更改为hashmap可以实现针对您问题的最佳解决方案。

Convert your array to list using Arrays.asList() and then use the collections api to get the count. 使用Arrays.asList()将数组转换为列表,然后使用collections api获取计数。

Collections.frequency(Collection c, Object o) Collections.frequency(Collection c,Object o)

Updated with the implementation 更新了实现

import java.util.AbstractList;
import java.util.Collections;
import java.util.List;

public class SortingInLinearTime {
    public static int[][] howMany( int[] n){

        // Makes a double array list where the second value is occurrence of the first value.
        int[][] a = new int[n.length][2]; 


        for(int i = 0; i < n.length; i++){
            int count = Collections.frequency(asList(n), n[i]);
            a[i][0] = n[i];
            a[i][1] = count;
         }

        // printer helper function
        for(int i = 0; i < n.length; i++){ 
            System.out.print(a[i][0] + " occurs ");
            System.out.println(a[i][1] + " times");
        }
        return a;
    }


    public static List<Integer> asList(final int[] is)
    {
        return new AbstractList<Integer>() {
                public Integer get(int i) { return is[i]; }
                public int size() { return is.length; }
        };
    }


    public static void main(String[] args) {
        int[] testArray = {1, 2, 3, 1, 2, 3, 4};
        System.out.print(howMany(testArray));
    }
}

You're making this way harder than it needs to be both by looping over the array twice and by using an array to store your result. 通过遍历两次数组和使用数组存储结果,您将使这种方法比需要的难度更大。 Try this: 尝试这个:

public class SortingInLinearTime {
    public static Hashtable<Integer, Integer> howMany(int[] n){
        Hashtable<Integer, Integer> toRet = new Hashtable<Integer, Integer>();
        for (int i = 0; i < n.length; i++) {
            if (!toRet .containsKey(n[i])) {
                toRet.put(n[i], 1);
            } else {
                toRet.put(n[i], toRet.get(n[i]) + 1);
            }
        }
        return toRet;
    }

    public static void main(String[] args) {
        int[] testArray = {1, 2, 3, 1, 2, 3, 4};
        Hashtable<Integer, Integer> counts = howMany(testArray);
        Set<Integer> keys = counts.keySet();
        for(Integer key : keys){
            System.out.println(key + " occurs " + counts.get(key) + " times.");
        }
    }
}

This has several advantages. 这具有几个优点。 It will not break if you pass an array with large numbers, like {1, 11, 203, 203} , which your current implementation cannot handle. 如果传递具有当前执行无法处理的大数的数组(如{1, 11, 203, 203} ,则不会中断。 It does not use extra space by declaring an array with many elements that you do not need. 通过声明包含许多不需要的元素的数组,它不会使用额外的空间。 Most important, it works. 最重要的是,它有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM