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

后端 未结 11 1599
后悔当初
后悔当初 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:37

    In continuation to the pseudo-code what you've written try the below written code:-

    public static void fetchFrequency(int[] arry) {
            Map newMap = new TreeMap(Collections.reverseOrder());
            int num = 0;
            int count = 0;
            for (int i = 0; i < arry.length; i++) {
                if (newMap.containsKey(arry[i])) {
                    count = newMap.get(arry[i]);
                    newMap.put(arry[i], ++count);
                } else {
                    newMap.put(arry[i], 1);
                }
            }
            Set> set = newMap.entrySet();
            List> list = new ArrayList>(set);
            Collections.sort(list, new Comparator>() {
    
                @Override
                public int compare(Entry o1, Entry o2) {
                    return (o2.getValue()).compareTo(o1.getValue());
                }
            });
    
            for (Map.Entry entry : list) {
                System.out.println(entry.getKey() + " ==== " + entry.getValue());
                break;
            }
            //return num;
        }
    

提交回复
热议问题