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.
即:已知一个长度为n的数组,求出现半数以上的元素。
方法:
1. 使用HashMap存储元素和出现的次数
2.Sort排序
3. Majority Voting Algorithm
Sort排序
对数组进行排序,元素出现次数超过[n/2]的元素。肯定位于数组索引为length/2的位置。很简单,数组元素出现的次数既然超过了[n/2],排序之后肯定位于数组的中间。
class Solution {
public int majorityElement(int[] nums) {
Arrays.sort(nums);
return nums[nums.length/2];
}
}
Majority Voting Algorithm
参考:
https://gregable.com/2013/10/majority-vote-algorithm-find-majority.html
http://blog.csdn.net/pi9nc/article/details/9355293
算法的基本思想
遍历数组,每出现一对不同的元素,就把他们删除(那么在剩下的子数组中,原出现次数超过[2]的元素在子数组中出现的次数也肯定超过[2]),知道数组为空或者只剩下一个元素。不难证明,如果存在元素e出现频率超过半数,那么数组中最后剩下的就只有e。当然,最后剩下的元素也可能并没有出现半数以上。比如说数组是[1, 2, 3],最后剩下的3显然只出现了1次,并不到半数。排除这种false positive情况的方法也很简单,只要保存下原始数组,最后扫描一遍验证一下就可以了。
算法的步骤
- 现在来分析一下复杂度。删除元素可以在常数时间内完成,但找不同元素似乎有点麻烦。实际上,我们可以换个角度来想,用一个小trick来重新实现下该算法。
- 算法分为两次O(n)遍历输入数组:
In the first pass, we generate a single candidate value which is the majority value if there is a majority. The second pass simply counts the frequency of that value to confirm. The first pass is the interesting part.
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 = 0
count = 0
for value in input
if count == 0
candidate = value
if candidate == value
count += 1
else
count -= 1
At the end of all of the inputs, the candidate will be the majority value if a majority value exists. A second O(N) pass can verify that the candidate is the majority element (an exercise left for the reader).
插上完整代码:
public int majorityElement(int[] nums)
{
// return HashMethod(nums);
int candidate=0;
int count=0;
for (int i = 0; i <nums.length ; i++) {
if(count == 0)
candidate=nums[i];
if(candidate == nums[i])
count++;
else
count--;
}
count=0;
for (int i = 0; i < nums.length ; i++) {
if (nums[i] == candidate)
count++;
}
if(count > Math.floor(nums.length/2.0))
return candidate;
throw new RuntimeException("不存在Majority Element");
}