Hdu1004 Let the Balloon Rise

Let the Balloon Rise

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 114532 Accepted Submission(s): 44832


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

題意:輸入n個顏色,輸出出現次數最多的顏色。


思路:我的方法是用List集合,三個list,分別記錄 n個輸入,顏色數目和出現次數,list2和list3對應,之後遍歷list1,記錄每種顏色出現的次數,然後找到最大的,輸出。其實也可以把數據存在數組中,排序,找出最大出現次數,再遍歷根據這個次數找尋並輸出顏色,這裏主要複習了一下List的使用,也熟悉了List中的set方法。


import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;


public class Main {

	public static void main(String[] args) {
         Scanner sc = new Scanner(System.in);
         while(sc.hasNext()){
        	 int n = sc.nextInt();
        	 if(n==0){
        		 break;
        	 }
        	 List<String> list1 = new ArrayList<String>();
        	 List<String> list2 = new ArrayList<String>();
        	 List<Integer> list3 = new ArrayList<Integer>();
        	 
        	 while(n-->0){
        		 String str = sc.next();
        		 list1.add(str);
        		 if(!list2.contains(str)){
        			 list2.add(str);
        		 }
        	 }
        	 for(int i=0;i<list2.size();i++){
        		 list3.add(0);
        	 }
        	 for(int i=0;i<list1.size();i++){
        		 for(int j=0;j<list2.size();j++){
        			if(list1.get(i).equals(list2.get(j))){
        				list3.set(j, list3.get(j)+1);
        				break;
        			}
        		 }
        	 }
        	 int max=0;
        	 int pos=0;
        	 for(int i=0;i<list3.size();i++){
        		 if(list3.get(i)>max){
        			 max=list3.get(i);
        			 pos=i;
        		 }
        	 }
        	 System.out.println(list2.get(pos));
         }
	}

}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章