Write a mode method in Java to find the most frequently occurring element in an array

前端 未结 14 2532
清酒与你
清酒与你 2020-11-29 07:17

The question goes:

Write a method called mode that returns the most frequently occurring element of an array of integers. Assume that the array has at le

14条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-29 07:21

    Here, I have coded using single loop. We are getting mode from a[j-1] because localCount was recently updated when j was j-1. Also N is size of the array & counts are initialized to 0.

            //After sorting the array 
            i = 0,j=0;
            while(i!=N && j!=N){
                if(ar[i] == ar[j]){
                    localCount++;
                    j++;
                }
                else{
                    i++;
                    localCount = 0;
                }
                if(localCount > globalCount){
                    globalCount = localCount;
                    mode = ar[j-1]; 
                }
            }
    

提交回复
热议问题