lintcode 选票最多的人

lintcode 选票最多的人

描述

给定一个包含候选人姓名的数组. 数组中一个候选人的名字代表他获得了一张选票. 返回的票最多的人的名字.

样例

样例 1:

输入:
[
“John”, “Johnny”, “Jackie”,
“Johnny”, “John”, “Jackie”,
“Jamie”, “Jamie”, “John”,
“Johnny”, “Jamie”, “Johnny”,
“John”
]
输出: “John”
解释:
列表里共出现了4个候选人: “John”, “Johnny”,
“Jamie”, “Jackie”. John 和 Johny 同样获得了
最高数额的选票, 而因为 John 字典序更小, 所以返回他.
样例 2:

输入:
[
“John”, “Johnny”, “Jackie”,
“Johnny”, “John”, “Jackie”,
“Jamie”, “Jamie”, “John”,
“Johnny”, “Johnny”, “Johnny”,
“John”
]
输出: “Johnny”

思路

使用map记录下名字和选票个数,最后遍历这个map,得到选票最多的人

代码

class Solution {
public:
    /**
     * @param votes: The array of names of candidates in the election.
     * @return: The name of the candidate who has the most votes.
     */
    string candidateWithTheMostVotes(vector<string> &votes) {
        // Write your code here
        map<string, int> m;
        for (int i = 0; i < votes.size(); i++)
            m[votes[i]]++;
        int t = INT_MIN;
        string res;
        for (map<string, int>::iterator it = m.begin(); it!=m.end(); it++) {
            if (it->second > t) {
                t = it->second;
                res = it->first;
            }
        }
        return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值