题目如下:
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.
分析如下:
从头到尾扫描一遍数组,记录当前的majority element的count。
我的代码:
// 259ms
public class Solution {
public int majorityElement(int[] num) {
if(num.length < 3) return num[0];
int majority = num[0];
int count = 1;
//1,1,1,1,2,1,3,1,2,2,2,2,2,2,
for (int i = 1; i < num.length; ++i) {
if (count == 0) {
majority = num[i];
++count;
} else if (num[i] == majority) {
++count;
} else {
--count;
}
}
return majority;
}
}