题目如下
给定一个大小为 n 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。
你可以假设数组是非空的,并且给定的数组总是存在众数。
示例 1:
输入: [3,2,3]
输出: 3
示例 2:
输入: [2,2,1,1,1,2,2]
输出: 2
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/majority-element
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
我的代码在vs上编译通过且有正确结果 但是oj上编译出错
错误信息
solution.cpp: In member function majorityElement
Line 17: Char 32: error: control reaches end of non-void function [-Werror=return-type]
vector> list;
^~~~
cc1plus: some warnings being treated as errors
代码如下
class Solution {
public:
int majorityElement(vector<int>& nums) {
vector<pair<int, int>> list;
for (auto a : nums) {
bool has = false;
for (int b = 0; b<list.size();b++) {
if (list[b].first == a) {
list[b].second+=1;
has = true;
}
}
if(has==false) {
list.push_back(make_pair(a, 1));
}
has = false;
}
for (auto b : list) {
if (b.second > nums.size()/2)
return b.first;
}
}
};