【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.


http://blog.csdn.net/u012162613/article/details/42080621

http://bookshadow.com/weblog/2014/12/22/leetcode-majority-element/

解法很多:
  1. Runtime: O(n2) — Brute force solution: Check each element if it is the majority element. 蛮力法: 依次检查每一个元素是否为众数
  2. Runtime: O(n), Space: O(n) — Hash table: Maintain a hash table of the counts of each element, then find the most common one. 哈希表: 维护一个每一个元素出现次数的哈希表, 然后找到出现次数最多的元素
  3. Runtime: O(n log n) — Sorting: Find the longest contiguous identical element in the array after sorting. 排序: 在排序后找出连续重复出现次数最多的元素
  4. Average runtime: O(n), Worst case runtime: Infinity — Randomization: Randomly pick an element and check if it is the majority element. If it is not, do the random pick again until you find the majority element. As the probability to pick the majority element is greater than 1/2, the expected number of attempts is < 2. 随机算法: 随机选取一个元素计算其是否为众数. 如果不是, 就重复上一步骤直到找到为止。 由于选出众数的概率 > 1 / 2, 因此期望的尝试次数 < 2
  5. Runtime: O(n log n) — Divide and conquer: Divide the array into two halves, then find the majority element A in the first half and the majority element B in the second half. The global majority element must either be A or B. If A == B, then it automatically becomes the global majority element. If not, then both A and B are the candidates for the majority element, and it is suffice to check the count of occurrences for at most two candidates. The runtime complexity, T(n) = T(n/2) + 2n = O(n log n). 分治法: 将数组拆成2半, 然后找出前一半的众数A和后一半的众数B。则全局众数要么是A要么是B。 如果 A == B, 则它自然而然就是全局众数。 如果不是, 则A和B都是候选众数, 则至多只需要检查这两个元素的出现次数即可。 时间复杂度, T(n) = T(n/2) + 2n = O(n log n).
  6. 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:
    1. If the counter is 0, we set the current candidate to x and the counter to 1.
    2. 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). 

    Moore投票算法: 我们维护一个当前的候选众数和一个初始为0的计数器。遍历数组时,我们看当前的元素x:

    • 如果计数器是0, 我们将候选众数置为 x 并将计数器置为 1
    • 如果计数器非0, 我们根据x与当前的候选众数是否相等对计数器+1或者-1
    • 一趟之后, 当前的候选众数就是所求众数. 时间复杂度 = O(n).
  7. 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. 位操作法: 我们需要32次迭代, 每一次计算所有n个数的第i位的1的个数。由于众数一定存在,那么或者1的个数 > 0的个数 或者反过来(但绝不会相同)。 众数的第i位一定是计数较多数字

http://stackoverflow.com/questions/11041405/why-dict-getkey-instead-of-dictkey



方法1: 哈希表

出现的次数,大于[n/2]的只能有一个

http://yucoding.blogspot.jp/2015/03/leetcode-question-majority-element.html


哈希表:


class Solution(object):
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        
        #dict={}
        
        d=dict()
        
        for n in nums:
            
            d[n]=d.get(n,0)+1
            
            if d[n]>len(nums)/2:
                return n


方法2: Moore投票

这个方法可行的前提:你可以假设数组是非空的并且数组中的众数永远存在

否则返回值会是错误的数

既然最多元素出现了n/2次,就可以用抵消的思想,用它和与它不相等的元素一一相消,剩下的一定就是最多的那个元素

一种对冲思路:一旦相邻的两个元素不同,就把这两个元素对冲抵消掉;由于众数的出现频次大于数据其他所有元素出现频次之和,所以这种对冲抵消最后剩下的一定是众数。

http://bookshadow.com/weblog/2014/12/22/leetcode-majority-element/


class Solution(object):
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        
        candidate=None
        count=0
        
        for n in nums:
            if count==0:           #前面的都被两两不同项目抵消了
                candidate=n
                count+=1
            elif n==candidate:     #如果前面的candidate的count还有剩余,当n=candidate时,count就加1
                count+=1
            else:                  #如果前面的candidate的count还有剩余,当n!=candidate时,就抵消掉一个
                count-=1
        return candidate           #因为假设一定存在majority了,所以最后剩下的一定是majority


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值