本文共 1373 字,大约阅读时间需要 4 分钟。
*输入:1 1 1 2 2 3 3 3 3 3
*输出:3 3 3 3 3 1 1 1 2 2 注:3 出现5次,1出现3次,2出现2次。代码实现如下:
import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import java.util.HashMap;import java.util.Iterator;import java.util.List;import java.util.Map;import java.util.Map.Entry;import java.util.Set;/** * 对数组按频率排序输出 *输入:1 1 1 2 2 3 3 3 3 3 *输出:3 3 3 3 3 1 1 1 2 2 */ public class SortByFrequency { public static void main(String[] args) { int[] array = { 1,1,1,2,2,3,3,3,3,3}; Listres = sortByFrequency(array); System.out.println(res.toString()); } public static List sortByFrequency(int[] array) { HashMap map = new HashMap (); for (int i = 0; i < array.length; i++) { if (map.get(array[i]) == null) { map.put(array[i], 1); }else { map.put(array[i], map.get(array[i]) + 1); } } Set > keySet = map.entrySet(); List > mapEntries = new ArrayList >(keySet); Collections.sort(mapEntries,new Comparator >() { public int compare(Map.Entry o1, Map.Entry o2) { // o1.getValue() - o2.getValue() 升序 // o2.getValue() - o1.getValue() 降序 return (o2.getValue() - o1.getValue()); } }); List res = new ArrayList (); for (int i = 0; i < mapEntries.size(); i++) { for (int j = 0; j < mapEntries.get(i).getValue(); j++) { res.add(mapEntries.get(i).getKey()); } } return res; }}
转载地址:http://cvdgi.baihongyu.com/