水过杭电OJ hdu1004

Java代码

import java.util.*;
public class Main {
    public static void main(String[] args) {
        String color;
        Scanner scanner = new Scanner(System.in);
        HashMap 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 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 balloons;
    map::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);//关闭
}



你可能感兴趣的:(Java,算法,杭电,OJ,算法,ACM,Aglorithm)