题目概述:

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 integerdef majorityElement(self, num):d = {}l = len(num)for i in num:if d.has_key(i):d[i] += 1if d[i] > l/2:return ielse:d[i] = 1if d[i] > l/2:return i

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

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

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

【leetcode】Majority Element相关推荐

  1. 【LeetCode】309. Best Time to Buy and Sell Stock with Cooldown 最佳买卖股票时机含冷冻期(Medium)(JAVA)

    [LeetCode]309. Best Time to Buy and Sell Stock with Cooldown 最佳买卖股票时机含冷冻期(Medium)(JAVA) 题目地址: https: ...

  2. 【Leetcode】100. 相同的树

    题目 给定两个二叉树,编写一个函数来检验它们是否相同. 如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的. 示例 1: 输入: 1 1/ \ / \2 3 2 3[1,2,3], [1 ...

  3. 【leetcode】85. Maximal Rectangle 0/1矩阵的最大全1子矩阵

    1. 题目 Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing only 1 ...

  4. 【leetcode】486. Predict the Winner

    题目如下: Given an array of scores that are non-negative integers. Player 1 picks one of the numbers fro ...

  5. 【leetcode】132. Palindrome Partitioning II

    题目如下: 解题思路:本题是[leetcode]131. Palindrome Partitioning的升级版,要求的是求出最小cuts,如果用[leetcode]131. Palindrome P ...

  6. 【leetcode】86. Partition List

    题目如下: Given a linked list and a value x, partition it such that all nodes less than x come before no ...

  7. 【Leetcode】103. 二叉树的锯齿形层次遍历

    题目 给定一个二叉树,返回其节点值的锯齿形层次遍历.(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行). 例如: 给定二叉树 [3,9,20,null,null,15,7], 3 ...

  8. 【Leetcode】79.单词搜索

    题目 给定一个二维网格和一个单词,找出该单词是否存在于网格中. 单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中"相邻"单元格是那些水平相邻或垂直相邻的单元格.同一个单元格 ...

  9. 【leetcode】 算法题1 两数之和

    [leetcode] 算法题1 两数之和 问题   给定一个整数数组和一个目标值,找出数组中和为目标值的两个数. 你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用. 示例: 给定 nums ...

最新文章

  1. Windows下Python 3.6 安装BeautifulSoup库
  2. mapreduce yarn内存参数
  3. 面向对象三大特性总结
  4. 山东大学2021-2022学年校历
  5. CPU的温度是360的准还是鲁大师的准?
  6. Vue2+Vant2:一个可定制图标的简易扫雷小游戏
  7. Chaos Mesh介绍
  8. 目标检测 | 盘点提升小目标检测的思路
  9. OpenGL_Qt学习笔记之_03(平面图形的着色和旋转)
  10. 习惯的力量在于不由主——知道顶个球用,成为习惯才是你的
  11. 论文图片格式要求具体有哪些?
  12. springboot 生成二维码
  13. 关于使用Pytorch时,训练集模型表现很好但测试集模型表现极差的原因
  14. 仙剑3安卓移植版_仙剑奇侠传3安卓版
  15. 实验一 基于TCP和UDP的客户端和服务器端
  16. 程序设计思维与实践 CSP-M4
  17. 微软认证系统工程师(MCSE)
  18. 线代第三章 向量(线性表出、线性相关)
  19. CPOFDM-16QAM性能仿真,输出接收端的星座图
  20. 单片机tcp ip协议c语言,单片机TCP IP协议栈实现的原理

热门文章

  1. Ubuntu 系统进不去 左上角减号
  2. 如何确定oracle进程,Oracle DBWR进程的工作流程以及和其他进程的协调工作!
  3. Python_列表2
  4. mysql5.5删除干净_MySql5.5 安装及卸载
  5. python实现选择文件_用tkinter 实现从文件夹选择文件并显示
  6. android 宽度动画,android – ObjectAnimator对LinearLayout宽度进行动画处理
  7. linux 下wn725无线网卡驱动,TL-WN725N V3无线网卡驱动移植与wireless工具wpa_supplicant-2.6...
  8. SecureCRT日志上添加时间戳
  9. libusb的交叉编译
  10. 2021高通AI应用创新大赛-创新赛道-垃圾分类识别 第二次讨论会