Most common values in an array

后端 未结 4 993
时光说笑
时光说笑 2021-01-14 22:25

How would I go about finding the three most common elements in an array? I am working with an array of length 10,000 with elements = random integer from 0-100.

I was

4条回答
  •  攒了一身酷
    2021-01-14 23:21

    There are probably better ways to do this, but this is a way. I just printed the mode array, but you can sort it to see what number actually occurred the most. This is simple because we know the upper and lower bounds of the numbers we are messing with, but if you don't know those bounds then you need to take the advice Stephen C gave.

    public class Main {
    
        public static void main(String[] args) {
    
            int i;
            int value;
            //one greater than max value because Math.random always returns a value less than 1.0
            //this number also works good for our mode array size
            int maxValue = 101;
            int[] originalArray = new int[10000];
            int[] modeArray = new int[maxValue];
    
            for(i = 0; i < originalArray.length; i++){
                value = (int) (Math.random() * maxValue);
                originalArray[i] = value;
            }
    
    
            for(i = 0; i < originalArray.length; i++){
                modeArray[originalArray[i]] += 1;
            }
    
            for(i = 0; i < modeArray.length; i++){
                System.out.println("Number " + i + " occurred " + modeArray[i] + " times");
            }
    
        }
    
    }
    

提交回复
热议问题