1. 程式人生 > >2018/12/08 PAT刷題 L1-034 點贊

2018/12/08 PAT刷題 L1-034 點贊

題目明確規定了數字的範圍, 那麼就可以使用陣列來做.

再思考一下, 如果沒有規定數字的範圍, 也就是要使用容器來做這題, 那該怎麼寫呢.

import java.io.BufferedReader;
import java.io.InputStreamReader;
 
public class Main {
 
    public static void main(String[] args) throws Exception{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        
int N = Integer.parseInt(br.readLine()); int b[] = new int[1001]; // 由於又明確數字表明總共的數字小於等於1000個, 因此使用陣列是合理的. for (int i = 0; i < N; i++) { String[] str = br.readLine().split(" "); int a = Integer.parseInt(str[0]); for (int j = 1; j <= a; j++) { // 原先是j<a, 有兩個點錯誤, 應該是j<=a , 應為輸入的數字總共是a+1個.
b[Integer.parseInt(str[j])]++; } } int max = 0; int maxindex = 0; for (int i = 0; i <= 1000; i++) { if (max < b[i]) { max = b[i]; maxindex = i; } if (b[i] == max && i > maxindex) { max
= b[i]; maxindex = i; } } System.out.println(maxindex + " " + max); } }