Let the Balloon Rise
Problem Description
Contest time again! How excited it is to see balloons floating around. But to tell you a secret, the judges’ favorite time is guessing the most popular problem. When the contest is over, they will count the balloons of each color and find the result.
This year, they decide to leave this lovely job to you.
Input
Input contains multiple test cases. Each test case starts with a number N (0 < N <= 1000) – the total number of balloons distributed. The next N lines contain one color each. The color of a balloon is a string of up to 15 lower-case letters.
A test case with N = 0 terminates the input and this test case is not to be processed.
Output
For each case, print the color of balloon for the most popular problem on a single line. It is guaranteed that there is a unique solution for each test case.
Sample Input
5
green
red
blue
red
red
3
pink
orange
pink
0
Sample Output
red
pink
。。。不想多说,题目本来不是很难,但一开始调试的时候总出现输入溢出的问题,调到心累,后来网上查了一下资料,还是没找到问题,第二天自己重新写了一遍,发现竟然好了,内心感觉有一万头草泥马在奔腾…….
最后还是不知道当时出了什么bug。。。
import java.util.HashMap;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO 自动生成的方法存根
Scanner in=new Scanner(System.in);
int n;
while((n=in.nextInt())>0)
{
in.nextLine(); //吸收掉换行符
HashMap<String,Integer> color=new HashMap<String,Integer>();//建立新的Map表
for(int i=0;i<n;i++)
{
String str=in.next();
if(color.containsKey(str)) //判断Map表内是否有与输入相同的Key键
{
color.put(str,color.get(str)+1);
}
else
{
color.put(str, 1);
}
}
String s="";
int max=0;
for(HashMap.Entry<String,Integer>entry:color.entrySet())//遍历Map表内的Value值
{
if(entry.getValue()>max)
{
max=entry.getValue();
s=entry.getKey();
}
}
System.out.println(s);
}
}
}
下面的是网上找的c代码,稍微完善了一下,其主要思想跟java的HashMap表的映射思想是类似的。
#include <stdio.h>
#include <string.h>
main(){
int n, i, j, t, max, num[1000];
char color[1000][16];
while(scanf("%d", &n) != EOF){
if(n){
num[0]=0;
scanf("%s", color[0]);
for(i=1; i <n; i++){
num[i]=0;
scanf("%s", color[i]);
for(j=0; j <i; j++)
if(strcmp(color[i], color[j])==0) num[i] +=1;
}
max=num[0];
t=0;
for(i=1; i <n; i++)
if(max <num[i]) {max =num[i]; t=i;}
printf("%s\n",color[t]);
}
}
}