Let the Balloon Rise
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 129323 Accepted Submission(s): 51086
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.
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.
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
翻译:就是找到输入几个字符串,找到最多的那个。
核心问题:你不知道会输入什么,因此无法预定义。不过题目还是非常简单,这里采用java,简单地使用map和list就可以解决。把字符串放到list中,用循环从list中取,如果这个键(比如green)map中没有,那就给他添加。有了,map取得值加1即可。
public class LetTheBalloonRise1004 { private static List<String> list; public static void main(final String[] args) throws Exception { initData(); List<String> mostPopularList = calculate(list); for (String s : mostPopularList) { System.out.println(s); } } private static void initData() { list = initStringList("green", "red", "blue", "blue", "red"); } private static List<String> initStringList(String... s) { List<String> list = new ArrayList<>(); Collections.addAll(list, s); return list; } private static List<String> calculate(List<String> list) { Map<String, Integer> map = new HashMap<>(); for (String s : list) { if (map.get(s) == null) { map.put(s, 1); } else { int formal = map.get(s); map.put(s, ++formal); } } //遍历map int max = 0; List<String> mostPopularList = new ArrayList<>();//考虑有多个最大的情况 for (Map.Entry<String, Integer> entry : map.entrySet()) { if (entry.getValue() > max) { //如果遍历发现更大的值,清空集合,因为之前里面可能有多个最大 mostPopularList.clear(); mostPopularList.add(entry.getKey()); max = entry.getValue(); } else if (entry.getValue() == max) { //如果有个值相等的,添加到后一位即可 mostPopularList.add(entry.getKey()); } } return mostPopularList; } }