描述
给定一个包含候选人姓名的数组. 数组中一个候选人的名字代表他获得了一张选票. 返回的票最多的人的名字.
样例
样例 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;
}
};