Leetcode169. Majority Element | Moore Voting

1.Description

Given an array nums of size n, return the majority element which appears more than n/2 times. And the majority element always exists.

2.Algorithms

Moore Voting O(n)

3.Analysis

Sort
At first, I tried quick sort algorithm. But its time complexity doesn’t meet the requirement.

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        sort(nums.begin(),nums.end());
        int times = floor(nums.size()/2);
        int cnt = 1;
        int a = nums[0];
        for(int i = 1;i < nums.size();i++){
            if(a != nums[i]){
                if(cnt > times){
                    return {a};
                }
                else{
                    a = nums[i];
                    cnt = 0;
                }
            }
            cnt++;
        }
        if(cnt > times) return {a};

        return 0;
    }
};

And there is a detail to optimize the code. Because the majority element appears more than n/2 times, after sorting, nums[n/2] must be the element we want. So it can be optimized like this.

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        if(nums.size() == 1) return nums[0];
        sort(nums.begin(),nums.end());
        return nums[nums.size()/2];
    }
};

Moore Voting
This algorithm can only be used when the majority element exists.
The core idea is that the number of different elements cancel each other out. ‘cnt == 0‘ means that the different elements that have been iterated so far have the same number of occurrence.

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int cnt = 1, ans = 0;
        for(int i = 1;i < nums.size();i++){
            if(nums[i] != nums[ans])
                cnt--;
            else
                cnt++;
            if(cnt == 0){
                ans = i;
                cnt++;
            }
        }
        return nums[ans];
    }
};
4. Complexity

sort
Time complexity: O(nlogn)
Space complexity: O(1)
Moore Voting
Time complexity: O(n)
Space complexity: O(1)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值