美文网首页
169. Majority Element

169. Majority Element

作者: 阿团相信梦想都能实现 | 来源:发表于2016-12-31 09:32 被阅读0次
hash table 
class Solution(object):
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        hash_table={}
        for num in nums:
            if num in hash_table:
                hash_table[num]+=1
            else:
                hash_table[num]=1
        return max(hash_table,key=lambda x:hash_table[x])
moore's voting algrithm 
class Solution(object):
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        candidate=nums[0]
        count=1
        for num in nums[1:]:
            if count==0:
                candidate=num
                count=1
            elif num ==candidate:
                count+=1
            else: 
                count-=1
        return candidate
class Solution(object):
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        #bit manipulation
        bit=[0]*32
        res=0
        for num in nums:
            for i in range(32):
                bit[i]+=(num>>i)&1
        for i, val in enumerate(bit):
            if val>len(nums)/2:
                
                
                res|=(1<<i) 
                if i==31:#negative number, 2's complement =val-2^N
                    res-=(1<<32)
        return res

相关文章

网友评论

      本文标题:169. Majority Element

      本文链接:https://www.haomeiwen.com/subject/ivevvttx.html