LeetCode: 169. Majority Element

LeetCode: 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.

Example 1:

Input: [3,2,3]
Output: 3

Example 2:

Input: [2,2,1,1,1,2,2]
Output: 2

解题思路

由于主元素(Majority Element) 的定义是出现次数超过半数的元素,且一定存在。因此,如果相邻元素不相等,直接丢弃,否则记录下它出现的次数, 留待和后面的比较。最后剩下的元素就主元素

AC 代码

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int lastNum = INT_MIN;
        int cnt = 0;
        for(size_t i = 0; i < nums.size(); ++i)
        {
            if(cnt == 0 || lastNum == nums[i])
            {
                ++cnt;
                lastNum = nums[i];
            }
            else
            {
                --cnt;
            }
        }

        return lastNum;
    }
};
全部评论

相关推荐

不愿透露姓名的神秘牛友
昨天 17:13
想去,但是听说加班强度实在难崩,所以拒绝了,现在有点心梗对面hr感觉也是实习生,打电话的时候怪紧张的,但是感觉人很好嘞
水中水之下水道的鼠鼠:哥们这不先去体验一下,不行再跑呗,大不了混个实习经历(有更好的转正offer就当我没说)
点赞 评论 收藏
分享
迟缓的斜杠青年巴比Q...:简历被投过的公司卖出去了,我前两天遇到过更离谱的,打电话来问我有没有意向报班学Java学习,服了,还拿我学校一个学长在他们那报班学了之后干了华为OD当招牌
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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