题解 | #数组中出现次数超过一半的数字#

数组中出现次数超过一半的数字

https://www.nowcoder.com/practice/e8a1b01a2df14cb2b228b30ee6a92163

#include <algorithm>
#include <vector>
#include <iostream>

using namespace std;
class Solution {
public:
   
    int MoreThanHalfNum_Solution(vector<int>& numbers) {
        if(numbers.size()==1){
            return numbers[0];
        }
         std::sort(numbers.begin(),numbers.end());   
         int Foud=numbers.size()/2;//中间次数
         int a=0;
         int firstpoint=1;
         int lastpoint=1;
         for(lastpoint=1;lastpoint<numbers.size();lastpoint++){
            if(numbers[lastpoint]==numbers[lastpoint-1]){//我这个firstpoint意义不大,本来想前后指针,发现不用
                numbers[firstpoint]=numbers[lastpoint];
                ++firstpoint;
                ++a;//及时更新次数
            }
            if(a>=Foud){
                return numbers[firstpoint-1];//返回上一个比较的值
            }
            if(numbers[lastpoint]!=numbers[lastpoint-1]){
                a=0;//不相等重置a
            }
         }
        
           return -1;
        }
};

全部评论

相关推荐

06-17 00:26
门头沟学院 Java
程序员小白条:建议换下项目,智能 AI 旅游推荐平台:https://github.com/luoye6/vue3_tourism_frontend 智能 AI 校园二手交易平台:https://github.com/luoye6/vue3_trade_frontend GPT 智能图书馆:https://github.com/luoye6/Vue_BookManageSystem 选项目要选自己能掌握的,然后最好能自己拓展的,分布式这种尽量别去写,不然你只能背八股文了,另外实习的话要多投,尤其是学历不利的情况下,多找几段实习,最好公司title大一点的
无实习如何秋招上岸
点赞 评论 收藏
分享
迟缓的斜杠青年巴比Q...:简历被投过的公司卖出去了,我前两天遇到过更离谱的,打电话来问我有没有意向报班学Java学习,服了,还拿我学校一个学长在他们那报班学了之后干了华为OD当招牌
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务