LeetCode(169) Majority Number

本文深入分析了在数组中查找出现次数超过一半的元素的算法,包括Moore投票算法及位运算方法。详细解释了算法原理、实现方式,并附上代码实例。

题目如下:

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.


分析如下:

居然几年前的一道baidu面试题也出现在leetcode上了,而且其实也来自几年前的《编程之美》中的找水王那到题目。这道题目的思路直接摘抄自官网:

Runtime: O(n) — Moore voting algorithm: We maintain a current candidate and a counter initialized to 0. As we iterate the array, we look at the current element x:
If the counter is 0, we set the current candidate to x and the counter to 1.
If the counter is not 0, we increment or decrement the counter based on whether x is the current candidate.
After one pass, the current candidate is the majority element. Runtime complexity = O(n).

我的代码:

//90ms
class Solution { 
public:
    int majorityElement(vector<int> &num) {
        if (num.size() == 0) return 0;
        int count = 1;
        int majority_number = num[0];
        for (int i = 1; i < num.size(); ++i) {
            if (num[i] == majority_number) {
                count++;
            } else if (count == 0) {
                majority_number = num[i]; 
            }else{
                count--;
            }
        }
        return majority_number;
    }
};

写完之后,发现这道题目还有官方的解答,里面个思路还挺有意思,用到了bit运算,虽然对这道题目而言,不一定合适,但是思路挺有意思。

Runtime: O(n) — Bit manipulation: We would need 32 iterations, each calculating the number of 1's for the ith bit of all n numbers. Since a majority must exist, therefore, either count of 1's > count of 0's or vice versa (but can never be equal). The majority number’s ith bit must be the one bit that has the greater count.



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值