博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【leetcode】Majority Element
阅读量:5157 次
发布时间:2019-06-13

本文共 3444 字,大约阅读时间需要 11 分钟。

题目概述:

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.

解题思路:

这个题解法很多,官方就给了七种

  • Runtime: O(n2) — Brute force solution: Check each element if it is the majority element.
  • Runtime: O(n), Space: O(n) — Hash table: Maintain a hash table of the counts of each element, then find the most common one.
  • Runtime: O(n log n) — Sorting: As we know more than half of the array are elements of the same value, we can sort the array and all majority elements will be grouped into one contiguous chunk. Therefore, the middle (n/2th) element must also be the majority element.
  • 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.
  • 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).
  • 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).
  • 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.
    Update (2014/12/24): Improve algorithm on the O(n log n) sorting solution: We do not need to 'Find the longest contiguous identical element' after sorting, the n/2th element is always the majority.

我用python的dict写了个,算在第二种方法里面吧:

class Solution2:    # @param num, a list of integers    # @return an integer    def majorityElement(self, num):        d = {}        l = len(num)        for i in num:            if d.has_key(i):                d[i] += 1                if d[i] > l/2:                    return i            else:                d[i] = 1                if d[i] > l/2:                    return i

另外借鉴了一下另一种思路:我们不断的同时移除两个不同的数,得到的最终的结果就是满足题意的数,这种思想可以延伸到出现次数大于n/k的情况(当然基于hash的方法也可以),就是同时移除k个不同的数,最后留下的结果就是满足题意的。

class Solution:    # @param num, a list of integers    # @return an integer    def majorityElement(self, num):        res = 0         c = 0        for i in num:            if c == 0:                res = i                c = 1            else:                if res == i:                    c += 1                else:                    c -= 1        return res

转载于:https://www.cnblogs.com/MrLJC/p/4230696.html

你可能感兴趣的文章
linux下的权限详解
查看>>
c++ 使用socket实现C/S端文件的下载传输
查看>>
windows下NPM安装
查看>>
完美PNG半透明窗体解决方案
查看>>
Linux安装Java开发环境
查看>>
[NOIP2017]宝藏
查看>>
怎么入门
查看>>
JavaScript精要
查看>>
全局变量、静态全局变量和全局常量
查看>>
数据标准化总结(数据预处理)
查看>>
2.hibernate初印象
查看>>
51nod 1106 质数检测
查看>>
机器人数目
查看>>
fs.appendFileSync()方法
查看>>
【快速幂】 模板
查看>>
不重启mysql情况修改参数变量
查看>>
Hdu 3342 Legal or Not
查看>>
从gitHub上拉取并运行项目
查看>>
screen
查看>>
IO扩展芯片
查看>>