Find the mode (most frequent value in an array) using a simple for loop?

前端 未结 4 699
栀梦
栀梦 2020-12-20 10:30

How do I find the mode (most frequent value in an array) using a simple for loop?

The code compiles with a wrong output.

Here is what I have:



        
4条回答
  •  Happy的楠姐
    2020-12-20 11:13

    First I sort the array by order and then I count occurrences of one number. No hashmaps only for loop and if statements.

    My code:

    static int Mode(int[] n){
        int t = 0;
        for(int i=0; i n[j]){
                    t = n[j-1];
                    n[j-1] = n[j];
                    n[j] = t;
                }
            }
        }
    
        int mode = n[0];
        int temp = 1;
        int temp2 = 1;
        for(int i=1;i= temp2){
                mode = n[i];
                temp2 = temp;
            }
        }
        return mode;
    }
    

提交回复
热议问题