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


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次的元素。嗯,会好好讲原理。

原创粉丝点击