本文共 1034 字,大约阅读时间需要 3 分钟。
转自:
/** * 使用HashMap提高性能。如果是自己定义的类,则要合理重写hashCode和equals方法 * @param a * @return */ public staticint getMostFrequentByMap(T a[]){ if(a == null||a.length == 0){ return 0; } int result = 0; int size = a.length; HashMap > severalMap = new HashMap<>(); for (int i = 0; i < size; i++) { T t = a[i]; //以元素本身为键,元素分配到的LinkedList为值 if(severalMap.get(t) != null){ severalMap.get(t).add(t); }else{ LinkedList temp = new LinkedList (); temp.add(t); severalMap.put(t, temp); } } //指向长度最大的集合 LinkedList largestList = null; //找到元素最多的集合 for (LinkedList tempList : severalMap.values()) { if(largestList == null){ largestList = tempList; continue; } if(tempList.size() > largestList.size()){ largestList = tempList; } result = largestList.size(); } return result; }
转载地址:http://brip.baihongyu.com/