水过杭电OJ hdu1004

Java代码

import java.util.*;
public class Main {
    public static void main(String[] args) {
        String color;
        Scanner scanner = new Scanner(System.in);
        HashMap<String, Integer> colorsMap = new HashMap<>();
        int N;
        while (scanner.hasNext()) {
            N = scanner.nextInt();
            if (0 == N) {
                break;
            }
            scanner.nextLine();
            while (N > 0) {
                N--;
                color = scanner.nextLine();
                if (colorsMap.containsKey(color)) {
                    //已存在
                    int oldValue = colorsMap.get(color);
                    colorsMap.replace(color, oldValue + 1);
                } else {
                    colorsMap.put(color, 1);
                }
            }
            ArrayList arrayList = new ArrayList<>(colorsMap.values());
            Collections.sort(arrayList);
            int maximum = (int) arrayList.get(arrayList.size() - 1);
            HashSet<String> colors = new HashSet<>(colorsMap.keySet());
            for (Object str : colors) {
                if (colorsMap.get(str) == maximum) {
                    System.out.println(str);
                    break;
                }
            }
            colorsMap.clear();
        }
    }
}

C++代码

代码参考http://blog.pureisle.net/archives/884.html

void hdu1004()
{
    freopen("inputdata.txt", "r", stdin);//输入数据重定向
    //0<N<=1000
    int N = 0;
    string color;
    map<string, int> balloons;
    map<string, int>::iterator p, m;
    while (cin >> N)
    {
        if (0 == N) break;
        balloons.clear();
        for (int i = 0; i < N; ++i)
        {
            cin >> color;
            balloons[color]++;
        }
        p = m = balloons.begin();
        for (p; p != balloons.end(); p++)
        {
            cout << "p->first:" << p->first << endl;//first是key
            cout << "p->second:" << p->second << endl;//second是value
            
            if (p->second > m->second) m = p;
        }
        cout << m->first << endl;
    }

    fclose(stdin);//关闭
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值