Description
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.
Solution
Sort, time O(nlogn), space O(1)
class Solution {
public int majorityElement(int[] nums) {
Arrays.sort(nums);
return nums[nums.length / 2];
}
}
HashMap
簡直懶得寫
Majority Voting Algorithm, time O(n), space O(1)
Majority Vote Alogrithm
A Linear Time Majority Vote Algorithm
算法的具體思路是:假設在給定長度為 n 的數組中,Majority Element 出現的次數是 k 次,那么非 Majority Element 的出現次數就為 n-k。如果我們能去掉這 n-k 個元素那么剩下的就全部是 Majority Element 了。
我們可以遍歷數組,當碰到兩個不一樣的數字時,我們將這兩個數字同時丟棄這兩個數字中可能有一個為 Majority Element,也可能兩個都不為Majority Element.因為k 大于 n/2,所以在最差情況下(每次移除不同數字時都包含一個Majority Element),我們仍然能夠保證最后得到的數字是Majority Element.
在網上看到的很多資料中,對這一步的解釋都是略微有些問題的。很多人簡單的將這一步解釋為:找到一個Majority Element,隨后找到一個 非Majority Element,并將他們一并移除,這其實是錯誤的。我們在循環的時候,并沒有辦法判定當前的數字是否為 Majority Element,所以在移除的時候,我們可能是移除了一個 Majority Element 和一個 非Majority Element,也有可能移除的是兩個非Majority Element。所以最后 count 的值是不確定的,但是它能夠保證在最差情況下,剩余的仍然是 Majority Element。
例如,[1,2,3,3,3] 和 [1,3,2,3,3] 這兩個數組最后得到的 count 分別為 3 和 1,但是這并不影響答案的正確性。
這也是前面提到的Majority Element的數量必須大于n/2的原因.
很容易算出最后剩余的Majority Element個數最少為: n - ((n - k) + (n - k)) = 2k - n。
class Solution {
public int majorityElement(int[] nums) {
int major = 0;
int count = 0;
for (int i = 0; i < nums.length; ++i) {
if (count == 0) {
major = nums[i];
++count;
} else if (major == nums[i]) {
++count;
} else {
--count;
}
}
return major;
}
}