Easy-题目11:169. Majority Element

题目原文:
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always exist in the array.
题目大意:
找出一个数组的主元素,即在数组中出现的次数>n/2.
分析:
使用repeatTimes变量记录主元素重复次数,每次遇到重复的就+1,不重复的就-1.减到0时就更新当前主元素。(利用主元素出现次数比其他数出现之和多这一性质。)
源码:(language:c)

int majorityElement(int* nums, int numsSize) {
    int i,mainElement,repeatTimes = 0;  

    //每次若不相同则减小这个计数,若相同则增加  
    for(i = 0;i<numsSize;i++) {  
        if(repeatTimes == 0){  
            mainElement = nums[i];  
            repeatTimes = 1;  
        }  
        else{  
            if(mainElement == nums[i])  
                repeatTimes++;  
            else  
                repeatTimes--;  
        }  
    }  
    return mainElement;  
}

成绩:
8ms,beats 36.16%.众数:8ms 63.84%
Cmershen的碎碎念:
此题好像是考研408模拟题中的一道题,听说也经常在面试中出现。一开始我想到的是用HashMap记录每个元素出现的次数,最大的就是主元素。但这样的空间复杂度就是O(n),而上述算法有更优的O(1)空间复杂度。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值