数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在

xiaoxiao2021-02-28  43

分析:我们通过将数组元素的值作为Map对象的key,value为数组元素出现的次数。遍历整个数组。然后对map对象按照value来进行倒排序,即value最大也就是出现次数最多的元素在前。最后根据次数返回map对象的键即可。

import java.util.*; public class Solution {     HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();     public int MoreThanHalfNum_Solution(int [] array) {         if(array.length==0 || array==null){             return 0;         }         for(int i=0;i< array.length;i++){             if(map==null){                 map.put(array[i],1);             }else{                 if(map.containsKey(array[i])){                     //map中已经存有该元素                     //获取该元素在map有几份,也就是在数组中出现了几次                     int count=map.get(array[i]);                     map.put(array[i],count+1);                 }else{                     //新元素                      map.put(array[i],1);                 }                              }         }         //按照值进行排序         ArrayList<Map.Entry<Integer,Integer>> list=sortMap(map);         if(list.get(0).getValue() > array.length/2){             return list.get(0).getKey();         }else{             return 0;         }     }     public ArrayList<Map.Entry<Integer,Integer>> sortMap(Map map){      List<Map.Entry<Integer, Integer>> entries = new ArrayList<Map.Entry<Integer, Integer>>(map.entrySet());      Collections.sort(entries, new Comparator<Map.Entry<Integer, Integer>>() {          public int compare(Map.Entry<Integer, Integer> obj1 , Map.Entry<Integer, Integer> obj2) {              return obj2.getValue() - obj1.getValue();          }      });       return (ArrayList<Map.Entry<Integer, Integer>>) entries;     } }

转载请注明原文地址: https://www.6miu.com/read-2400273.html

最新回复(0)