Find the element with highest occurrences in an array [java]

后端 未结 11 1577
后悔当初
后悔当初 2021-01-18 02:36

I have to find the element with highest occurrences in a double array. I did it like this:

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


        
11条回答
  •  無奈伤痛
    2021-01-18 03:35

    Solution 1: Using HashMap

    class test1 {
        public static void main(String[] args) {
    
        int[] a = {1,1,2,1,5,6,6,6,8,5,9,7,1};
        // max occurences of an array
        Map map = new HashMap<>();
          int max = 0 ; int chh = 0 ;
          for(int i = 0 ; i < a.length;i++) {
              int ch = a[i];
              map.put(ch, map.getOrDefault(ch, 0) +1);
          }//for
          Set> entrySet =map.entrySet();
    
          for(Entry entry : entrySet) {
              if(entry.getValue() > max) {max = entry.getValue();chh = entry.getKey();}
    
          }//for
        System.out.println("max element => " + chh);
        System.out.println("frequency => " + max);
        }//amin
    }
    /*output =>
    max element => 1
    frequency => 4
    
    */
    

    Solution 2 : Using count array

    public class test2 {
        public static void main(String[] args) {
             int[] a = {1,1,2,1,5,6,6,6,6,6,8,5,9,7,1};
        int max = 0 ; int chh = 0;
        int count[] = new int[a.length];
        for(int i = 0 ; i  max) {max = count[ch] ; chh = ch ;}
        }//for
             System.out.println(chh); 
        }//main
    }
    

提交回复
热议问题