问题描述
让气球上升:又是比赛时间!看到气球飘来飘去是多么激动啊。不过告诉你一个秘密,评委们最喜欢的时间就是猜最热门的问题了。比赛结束后,他们将计算每种颜色的气球并找出结果。
今年,他们决定把这份可爱的工作留给你。
输入
输入包含多个测试用例。每个测试用例都以数字 N (0 < N <= 1000) 开头——分发的气球总数。接下来的 N 行每行包含一种颜色。气球的颜色是一串最多15个小写字母。N = 0 的测试用例终止输入,并且不处理该测试用例。
输出
对于每种情况,将出现最多的气球颜色打印在一行上。保证每个测试用例都有唯一的解决方案。
输入样例
5
green
red
blue
red
red
3
pink
orange
pink
0
输出样例
red
pink
程序代码:
方法一:采用ArrayList动态数组
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Ball1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNextInt()) {
int n = sc.nextInt();
if(n<=0) break;
ArrayList<Balloon> list = new ArrayList<Balloon>();
for(int i=1;i<=n;i++) {
String ball=sc.next();//读取气球的颜色
boolean isexist = false;//假定这个颜色不存在
for(int j=0;j<list.size();j++) {
if(list.get(j).color.equals(ball)) {
list.get(j).count++;//这个颜色的气球又多了一次
isexist = true;
break;
}
}
if(isexist==false) {
list.add(new Balloon(ball, 1));
}
}
Collections.sort(list);
System.out.println(list.get(0).color);
}
}
}
class Balloon implements Comparable<Balloon>{
public String color;
public int count;
public Balloon(String color, int count) {
this.color = color;
this.count = count;
}
@Override
public int compareTo(Balloon other) {
return other.count-this.count;
}
}
方法二:采用Map键值对的方法
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Ball2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNext()) {
int n = sc.nextInt();
if(n<=0) break;
Map<String,Integer> map = new HashMap<String,Integer>();
for(int i=1;i<=n;i++) {
String color = sc.next();
Integer count = map.get(color);
if(count==null) {//如果颜色第一次出现,次数为1
count = new Integer(1);
} else {//颜色已经存在,次数+1
count = new Integer(count.intValue()+1);
}
map.put(color, count);
}
int max_count = -1;
String more_color = "";
for(Object s:map.keySet()) {
int c = map.get(s);
if(max_count<c) {
max_count = c;
more_color = (String) s;
}
}
System.out.println(more_color);
}
}
}