博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
笔试-给定数组,按出现频率递减输出到链表中
阅读量:4283 次
发布时间:2019-05-27

本文共 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}; List
res = 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/

你可能感兴趣的文章
Git
查看>>
驱动 (3.2) copy_to_user
查看>>
getopt 解析
查看>>
文章标题
查看>>
linux前后台切换
查看>>
nmap
查看>>
uboot执行顺序main_loop
查看>>
uboot编译内容详解
查看>>
uboot Makefile 分析
查看>>
uboot网络验证
查看>>
烧写uboot
查看>>
QT安装
查看>>
QtCreator介绍
查看>>
QT工程实例
查看>>
pkg-config
查看>>
Linux内核分析-1/反汇编(堆栈)
查看>>
Linux内核分析-2/时间片轮转多道程序
查看>>
Linux内核分析-4/5/系统调用
查看>>
Linux内核分析-6/进程fork
查看>>
Linux内核分析-7/程序的装载(基于fork)
查看>>