版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
题目:
输入多个8位的id加城市的名字,23112411-beijing 这样,然后统计签到人数前三个城市,同一个ID城市多次签到同一个城市只记一次,次数相同时,则按城市首字母顺序排列。
示例:
输入:
34839946-beijing
34839934-beijing
34839946-beijing
34839946-shanghai
34839912-hangzhou
-1
输出:
city=beijing, citycount=2
city=hangzhou, citycount=1
city=shanghai, citycount=1
思路:
输入时通过一个HashMap将重复签到的数据过滤,然后再利用一个HashMap统计所有城市的签到次数,最后将HashMap中的数据排序。排序有多种选择:
①冒泡排序,新建String的数组,存储城市名,通过索引HashMap中的value将数组排序
②通过Collections.sort排序
详细的Collections.sort用法链接:https://www.cnblogs.com/yw0219/p/7222108.html?utm_source=itdadao&utm_medium=referral
代码:Collections.sort排序
public class Mafengwo1 implements Comparable<Mafengwo1> {
private String city;
private int citycount;
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public int getCitycount() {
return citycount;
}
public void setCitycount(int citycount) {
this.citycount = citycount;
}
public Mafengwo1(String city, int citycount) {
this.city = city;
this.citycount = citycount;
}
public Mafengwo1() {
}
static Map<String, Integer> map = new HashMap<String, Integer>();
static Map<String, Integer> map2 = new HashMap<String, Integer>();
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String str = new String();
str = in.next();
while (!str.equals("-1")) {
map.put(str, 1);
str = in.next();
}
in.close();
Mafengwo1 test = new Mafengwo1();
test.city(map);
}
public void city(Map<String, Integer> map) {
for (String str : map.keySet()) {
String str2 = new String();
str2 = str.substring(9);
map2.put(str2, map2.getOrDefault(str2, 0) + 1);
}
int i = 0;
List<Mafengwo1> empList = new ArrayList<>();
for (String k : map2.keySet()) {
Mafengwo1 emp = new Mafengwo1(k, map2.get(k));
empList.add(emp);
}
Collections.sort(empList, Comparator.reverseOrder());
while(i<3) {
System.out.println(empList.get(i));
i++;
}
}
@Override
public String toString() {
return " city=" + city + ", citycount=" + citycount;
}
@Override
public int compareTo(Mafengwo1 o) {
if (this.getCitycount() - o.getCitycount() == 0) {
return o.getCity().compareTo(this.getCity());
}
return this.getCitycount() - o.getCitycount();
}
}