⬆︎
×

[PAT-A] 1054 The Dominant Color

Hyplus目录

Java

import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String[] splits = br.readLine().split(" ");
        int n = Integer.parseInt(splits[1]);

        Map<String, Integer> map = new HashMap<>();
        for (int i = 0; i < n; i++) {
            splits = br.readLine().split(" ");
            for (String s : splits) {
                map.merge(s, 1, Integer::sum);
            }
        }

        int max = 0;
        String flag = "";
        for (String key : map.keySet()) {
            Integer value = map.get(key);
            if (value > max) {
                max = value;
                flag = key;
            }
        }
        System.out.println(flag);
    }
}

C++

#include <iostream>
#include <cstring>
#include <algorithm>
#include <unordered_map>

using namespace std;

const int N = 810;

int m, n;
unordered_map<int, int> colors;

int main() {
    scanf("%d%d", &m, &n);

    for (int i = 0; i < n; ++i)
        for (int j = 0; j < m; ++j) {
            int x;
            scanf("%d", &x);
            colors[x]++;
        }

    for (auto it: colors)
        if (it.second > m * n / 2) {
            printf("%d\n", it.first);
            break;
        }

    return 0;
};

发表评论