LeetCode-Majority Element
来源:互联网 发布:软件系统工程师培训 编辑:程序博客网 时间:2024/06/09 15:47
Majority Element
- Majority Element
- 题目描述
- 算法
- 1 暴力求解n2
- 2 桶排序 n较小
- 3 找中位数问题
- 4 Divide and conquer
- 5 Randomization
- 6 Boyer-Moore Algorithm
- Majority Element
1. 题目描述
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
2.算法
2.1 暴力求解(n^2)
对a中的元素,再遍历一次数组,计算出现的次数,同时更新出现次数最多的元素。
2.2 桶排序 (n较小)
初始化一个数组b,遍历一次a,b[a[i]]+=1;同时记录a中最大的数max
for 0:max;再从b中找出最大的值,其下标就是出现最多次的元素。
时间复杂度O(n)
2.3 找中位数问题
排序找中位数,最快的快排或者归并o(nlogn);
2.4 Divide and conquer
时间复杂度为O(nlogn),将数组分成两半,分别递归查找这两部分的多数元素,若两者相同,则为多数元素,若不同,则其中之一必为多数元素,判断其一即可
2.5 Randomization
平均时间复杂度为O(n)O(n),最坏情况为无穷大。随机选一个元素,判断其是否为多数元素。由于选中多数元素的概率大于1/2
2.6 Boyer-Moore Algorithm
the algorithm uses O(1) extra space and O(N) time
In the first pass, we need 2 values:
1. A candidate value, initially set to any value.
2. A count, initially set to 0.
For each element in our input list, we first examine the count value. If the count is equal to 0, we set the candidate to the value at the current element. Next, first compare the element’s value to the current candidate value. If they are the same, we increment count by 1. If they are different, we decrement count by 1.
翻译过来就是,首先我们需要定义两个值,一个为candidate,一个为count,设为0.
对数组中的每一个元素,我们检测count值,如果为0,set candidate为当前元素。
然后比较candidate与当前元素的值,如果相同,count+1,如果不一样,count减一
代码实现
candidate = 0count = 0for value in input: if count == 0: candidate = value if candidate == value: count += 1 else: count -= 1
最后,candidate的值为出现次数超过n/2的元素。再遍历一次O(n)确认candidate是不是答案,如果不是,则没有。
参考了gregable.com
下一篇博客 找出现n/3次的元素。嗯,会好好讲原理。
- 【leetcode】Majority Element II,Majority element algorithm
- Leetcode: Majority Element &Majority Element II
- Leetcode Majority Element
- leetcode 169-Majority Element
- 【leetcode 哈希表】Majority Element
- LeetCode:Majority Element
- leetcode:Majority Element
- leetcode: Majority Element
- [LeetCode] Majority Element
- leetcode 153: Majority Element
- leetcode Majority Element
- LeetCode:Majority Element
- leetcode:Majority Element
- [LeetCode] Majority Element
- Leetcode-Majority Element
- [leetcode]Majority Element
- [LeetCode]Majority Element
- Leetcode: Majority Element
- gerrit高可用部署
- SpringMVC 404问题解析
- Unicode 和 Utf-8的区别
- Git学习笔记三:Git分支
- 单节点安装OpenStack 之 安装环境准备
- LeetCode-Majority Element
- 【python 爬虫】识别网站所用技术
- 单例模式的5种实现方式,以及在多线程环境下5种创建单例模式的效率
- 【2017西安网络赛】E Maximum Flow
- POJ
- Linux命令之cut
- 【Summary】——>Web组·大三·Week1
- hosts文件的作用
- C语言返回2个变量的方法