Leetcode_Majority Element

136 篇文章 0 订阅
24 篇文章 0 订阅

Tag
Array/Divide and Conquer/Bit Manipulation
Difficulty
Easy
Description
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.
Code

  • Array:

Moore Voting Algorithm
每找出两个不同的element,即成对删除count–,否则count++
时间复杂度O(n)

class Solution:
        # @param {integer[]} nums
        # @return {integer}
        def majorityElement(self, nums):
            count=0
            major_Element=0
            for num in nums:
                if count==0:
                    major_Element=num
                    count=count+1
                else:
                    if num==major_Element:
                        count =count+1
                    else:
                        count = count-1
            return major_Element
  • Divide and Conquer
    将数组划分成两半,分别递归查找这部分的多数元素,如果相同,则为多数元素,否则为其中之一,判断其一即可
    时间复杂度O(nlogn)
class Solution(object):
    def majority(self,nums,left,right):
        if left == right:
            return nums[left]
        mid = (left+right)/2
        lm = self.majority(nums,left,mid)
        rm = self.majority(nums,mid+1,right)
        if lm == rm:
            return lm
        if nums[left:right+1].count(lm) > nums[left:right+1].count(rm):
            return lm
        else:
            return rm
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        return self.majority(nums,0,len(nums)-1)
  • Bit Manipulation
    统计int的32位上每一位的众数,每一位的众数即组成了Majority Element的每一位。
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;
    } 
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值