统计数组中出现次数做多的元素

216 阅读1分钟

一个整型数组,求数组中出现次数最多的元素。 思路

  • 创建map,元素为key,出现次数为value;
  • 第一次遍历map记录每个元素的次数;
  • 遍历map根据value找出最多的元素,输出key,即为出现次数最多的元素 java实现:
public static void main(String[] args) {
              int[] a = new int[]{1, 2, 2, 3,4,4,4,6,6};
              int count=a.length;
              Map<Integer, Integer> map = new HashMap<>();
              for (int i = 0; i <count ; i++) {
                     if (map.containsKey(a[i])) {
                            int b = map.get(a[i]) + 1;
                            map.put(a[i], b);
                     } else {
                            map.put(a[i], 1);
                     }
              }
              int max=0;int key=0;
              for (Map.Entry en : map.entrySet()) {
                     if ((int)en.getValue() > max) {
                            max=(int)en.getValue();
                            key=(int)en.getKey();
                     }
              }
              System.out.println(key);
       }