Darth squared 2019-08-29 22:21 采纳率: 0%
浏览 511

leetcode169求众数编译不过

题目如下

给定一个大小为 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;
}
}

};

  • 写回答

1条回答 默认 最新

  • qtchen_1988 2019-08-30 10:53
    关注

    在函数最后添加 return -1;

    原因:
    如果

    if (b.second > nums.size()/2) //永远为false就没有返回值了,典型函数结尾没有返回值
           return b.first;
    
    评论

报告相同问题?

悬赏问题

  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序