【leetcode】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.
解题思路:
这个题解法很多,官方就给了七种
- 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的更多相关文章
- 【leetcode】Majority Element (easy)(*^__^*)
Given an array of size n, find the majority element. The majority element is the element that appear ...
- 【10_169】Majority Element
今天遇到的题都挺难的,不容易有会做的. 下面是代码,等明天看看Discuss里面有没有简单的方法~ Majority Element My Submissions Question Total Acc ...
- 【数组】Majority Element II
题目: Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The alg ...
- 【leetcode】Remove Element
题目概述: Given an array and a value, remove all instances of that value in place and return the new len ...
- 【leetcode】Remove Element (easy)
Given an array and a value, remove all instances of that value in place and return the new length. T ...
- 【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 ...
- 【LeetCode】位运算 bit manipulation(共32题)
[78]Subsets 给了一个 distinct 的数组,返回它所有的子集. Example: Input: nums = [,,] Output: [ [], [], [], [,,], [,], ...
- 【LeetCode】分治法 divide and conquer (共17题)
链接:https://leetcode.com/tag/divide-and-conquer/ [4]Median of Two Sorted Arrays [23]Merge k Sorted Li ...
- 【LeetCode 229】Majority Element II
Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorit ...
随机推荐
- Android开发:关于WebView
原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 .作者信息和本声明.否则将追究法律责任.http://liangruijun.blog.51cto.com/3061169/647456 ...
- 教你一招:Excel中使用MID函数获取身份证中的出生年月日
MID字符串函数,作用是从一个字符串中截取出指定数量的字符 MID(text, start_num, num_chars) text被截取的字符 start_num从左起第几位开始截取(用数字表达 ...
- 【bzoj2281】 Sdoi2011—黑白棋
http://www.lydsy.com/JudgeOnline/problem.php?id=2281 (题目链接) 题意 一个1*n的棋盘,棋盘上一个隔一个的放着个黑棋和白棋,最左端是白棋,最右端 ...
- 使用IntelliJ IDEA 配置Maven(入门)
1. 下载Maven 官方地址:http://maven.apache.org/download.cgi 解压并新建一个本地仓库文件夹 2.配置本地仓库路径 3.配置maven环境变量 ...
- 浅谈:深入理解struts2的流程已经spring和struts2的整合
第一步:在tomcat启动的时候 1.在tomcat启动的时候,首先会加载struts2的核心过滤器StrutsPrepareAndExecuteFilter <filter> <f ...
- 利用Python【Orange】结合DNA序列进行人种预测
http://blog.csdn.net/jj12345jj198999/article/details/8951120 coursera上 web intelligence and big data ...
- 使用ASP.NET Web Api构建基于REST风格的服务实战系列教程【开篇】【持续更新中。。。】
最近发现web api很火,园内也有各种大神已经在研究,本人在asp.net官网上看到一个系列教程,原文地址:http://bitoftech.net/2013/11/25/detailed-tuto ...
- 安全测试及B/S C/S安全性比较
一.用户认证安全的测试要考虑问题: 1. 明确区分系统中不同用户权限 2. 系统中会不会出现用户冲突 3. 系统会不会因用户的权限的改变造成混乱 4. ...
- SearchLookUpEdit
参考资料: 慧都控件网-DevExpress开发资源 在GridControl控件中使用SearchLookUpEdit构建数据快速输入
- C#学习笔记
1.C#中[],List,Array,ArrayList的区别 [] 是针对特定类型.固定长度的. List 是针对特定类型.任意长度的. Array 是针对任意类型.固定长度的. ArrayList ...