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.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

两种解法,一种是排序后取中位数!

另外一种是用计数的方式,Moore voting algorithm 据说是叫这个,和选票一半以上的人当选一样,计票方法:如果是一张反对票一张赞成票则互相抵消。

class Solution(object):
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        ans = nums[0]
        cnt = 1        
        for i in xrange(1, len(nums)):
            if cnt == 0:
                cnt = 1
                ans = nums[i]
            elif nums[i] == ans:
                cnt += 1
            else:
                cnt -= 1        
        return ans

另外我自己的解法是每两位计数一次,计数重复出现的数,见注释示例:

class Solution(object):
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        #nums.sort()
        #return nums[len(nums)>>1]
        # 1 1 2=>1==1 ans=1, dup=2, last 2 dump it
        # 2 1 1=>2!=1, dup=0, ans=1
        # 1 1 1 2=>1=1, dup=2, ans=1, 1!=2 
        # 1 2 3 1 1 1=>1!=2, dup=0, 3!=1, dup=0, 1==1, dup=2, ans=1
        # 1 1 3 3 2 1 1=>1==1,dup=2, 3==3, dup-=2,dup=0, 2!=0, 1 is answer
        # 1 1 1 1 3 3 3 3 2 1 1=>
        ans = nums[0]
        dup_flag = 0
        i = 1
        while i<len(nums):
            if nums[i] == nums[i-1]: 
                if nums[i] == ans: # check if is prev ans
                    dup_flag += 2                
                else:
                    if dup_flag >= 2:
                        dup_flag -= 2
                    else:
                        dup_flag = 2
                        ans = nums[i]                                           
            i += 2
        if len(nums) & 1 and dup_flag == 0:
                return nums[-1]
        return ans

最后一种是位运算:

Bit Manipulation

Another nice idea! The key lies in how to count the number of 1's on a specific bit. Specifically, you need a mask with a 1 on the i-the bit and 0 otherwise to get the i-th bit of each element in nums. The code is as follows.

class Solution {
public:
    int majorityElement(vector<int>& nums) { int major = 0, n = nums.size(); for (int i = 0, mask = 1; i < 32; i++, mask <<= 1) { int bitCounts = 0; for (int j = 0; j < n; j++) { if (nums[j] & mask) bitCounts++; if (bitCounts > n / 2) { major |= mask; break; } } } return major; } };

转载于:https://www.cnblogs.com/bonelee/p/8654829.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值