题目概述:

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

【leetcode】Majority Element的更多相关文章

  1. 【leetcode】Majority Element (easy)(*^__^*)

    Given an array of size n, find the majority element. The majority element is the element that appear ...

  2. 【10_169】Majority Element

    今天遇到的题都挺难的,不容易有会做的. 下面是代码,等明天看看Discuss里面有没有简单的方法~ Majority Element My Submissions Question Total Acc ...

  3. 【数组】Majority Element II

    题目: Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The alg ...

  4. 【leetcode】Remove Element

    题目概述: Given an array and a value, remove all instances of that value in place and return the new len ...

  5. 【leetcode】Remove Element (easy)

    Given an array and a value, remove all instances of that value in place and return the new length. T ...

  6. 【leetcode】1287. Element Appearing More Than 25% In Sorted Array

    题目如下: Given an integer array sorted in non-decreasing order, there is exactly one integer in the arr ...

  7. 【LeetCode】位运算 bit manipulation(共32题)

    [78]Subsets 给了一个 distinct 的数组,返回它所有的子集. Example: Input: nums = [,,] Output: [ [], [], [], [,,], [,], ...

  8. 【LeetCode】分治法 divide and conquer (共17题)

    链接:https://leetcode.com/tag/divide-and-conquer/ [4]Median of Two Sorted Arrays [23]Merge k Sorted Li ...

  9. 【LeetCode 229】Majority Element II

    Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorit ...

随机推荐

  1. Java,来源于大神

    也许你学习了那么久的Java了,但如果有人问你什么是JavaEE?你会怎么回答他呢?在此我来谈谈关于JavaEE的相关技术.(仅是个人见解) 在谈JavaEE时,我们首先来了解一下Java平台.目前, ...

  2. mac 常用地址

    1.hosts   配置文件地址 /private/etc/hosts 2.apache 配置文件地址 /etc/apache2/httpd.conf 3.Xcode 插件地址 ~/Library/A ...

  3. TAC Beta版本 冲冲冲!!!

    一.Beta版本冲刺博客目录: 第一天 第二天 第三天 第四天 第五天 第六天 第七天 二.Beta版本需要改进完善的功能: service层传入参数的判断与提示以及各函数内的相应提示 界面改进.优化 ...

  4. WinForm------SimpleButton去掉点击时的边框

    设置属性

  5. Canvas绘制图形

    1.Canvas绘制一个蓝色的矩形 <!DOCTYPE html> <html> <head lang="en"> <meta chars ...

  6. Mysql 建立索引

  7. npapi插件开发流程与实例

    近期做NPAPI插件,网上的介绍还是比较多,但就是没有一个完整的例子,FQ也没找到,难得NPAPI要走向陌路了?就不去深究额,先解决目前遇到的问题. 现状:已有Activex(仅兼容IE32/64位浏 ...

  8. 微信服务号模板消息接口新增"设置行业"和"添加模板"及细节优化

    微信服务号模板消息可以向用户发送重要的服务通知,如信用卡刷卡通知,商品购买成功通知等.昨日,微信团队发布公告称模板消息新增“设置行业”和“添加模板”接口及细节优化,详细变动如下 模板消息[业务通知]自 ...

  9. PHP流式上传和表单上传(美图秀秀)

    最近需要开发一个头像上传的功能,找了很多都需要授权的,后来找到了美图秀秀,功能非常好用. <?php /** * Note:for octet-stream upload * 这个是流式上传PH ...

  10. Linux如何查看文件系统(磁盘使用情况)

    查看磁盘剩余空间: df -Th 用法:df [选项]… [文件]… 显示每个<文件>所在的文件系统的信息,默认是显示所有文件系统. 长选项必须用的参数在使用短选项时也是必须的. -a, ...