java刷题(7)
频率排序
给 定一个 int 数组,统计数组中每个数字出现的次数,并按数字出现的次数进行排序(从大到小),将结果以 Map 返回,其中 key 为数字出现的次数,value 为出现过 key 次的所有数字集合(从小到大排序)。
import java.util.*;
public class Solution {
public Map<Integer, List<Integer>> orderByFrequency(int[] nums) {
// write your code here
//获取每个数字出现的次数,并放入默认升序key的TreeMap中,key为数字,value为出现次数。
Map<Integer, Integer> treemap = new TreeMap<>();
for(int num : nums) {
Integer frequency = treemap.get(num);
frequency = null==frequency ? 1 : frequency+1;
treemap.put(num, frequency);
}
Iterator itr = treemap.keySet().iterator();
//创建降序key的TreeMap
Map<Integer, List<Integer>> result = new TreeMap<>(new Comparator<Integer>(){
@Override
public int compare(Integer a, Integer b) {
return b.compareTo(a);
}
});
//循环treemap,将value(出现次数)放入到result的key中,将key(数字)放入到result的value中。
while(itr.hasNext()) {
Integer key = (Integer)itr.next();
Integer value = treemap.get(key);
List<Integer> res = result.get(value);
if(null == res) {
res = new ArrayList<>();
result.put(value, res);
}
res.add(key);
}
return result;
}
}
import java.lang.reflect.*;
import java.util.*;
public class Main {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String in = sc.nextLine();
String[] str = in.replace("[", "").replace("]", "").trim().split(",");
int[] nums = new int[str.length];
for (int i = 0; i < str.length; i++) {
try {
nums[i] = Integer.parseInt(str[i].trim());
} catch (Exception e) {
nums[i] = 0;
}
}
Solution solution = new Solution();
System.out.println(solution.orderByFrequency(nums));
sc.close();
}
}
相关推荐
java1.7源码-javaAndLetCode:jdk1.7&1.8源码解析letcode刷题记录
java 1.7源码 javaAndLetCode jdk1.7&1.8源码解析letcode刷题记录
程序员考试刷题-OCA-Java-SE-7-Programmer-I:OCAJavaSE7ProgrammerI学习指南练习题(考试1Z0-8
程序员考试刷题OCA-Java-SE-7-Programmer-I 该存储库包含我对OCA Java SE 7 Programmer I Study Guide提供的练习的实现。 关于指南 OCA Java SE 7 程序员 I 学习指南(E. Finegan, R. Liguori) 旨在帮助您通过 Oracle 的Java SE 7 程序员 I考试,从而获得OCA Java SE 7 程序员认证。 本书包含编码示例、测试、练习等。 其目的是让您熟悉将在考试中展示的 Java 基础知识、概念、工具和技术。 关于考试 该(又名Java SE 7 Programmer I考试,又名Oracle Certified Associate考试,又名1Z0-803考试)涵盖了 Java 编程语言的基础知识和所有 Java 编程技术的概述(以及一些 UML)。 通过此考试,您可以获得Oracle Certified Associates Java SE 7 程序员认证。 完成后,您可以通过 获得Oracle 认证专家 Java SE 7 认证。 有关 Oracle 认证计划的更多信息:及其 . 练
Android代码-刷题自测安卓应用
脑残奥运 头大刷题安卓应用 截图 License Copyright 2017 ChyengJason Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the sp
基于java面试刷题系统论文.docx
jspm面试刷题系统
java刷题器(自用).zip
java刷题器(自用).zip


