题目描述
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.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
分析
参考:A Linear Time Majority Vote Algorithm
一个典型的算法,可以在一次遍历,时间复杂度是O(1),空间复杂度是O(1)的情况下完成。
代码
public static int majorityElement(int[] nums) {
int m = nums[0];
int c = 1;
for (int i = 1; i < nums.length; i++) {
if (m == nums[i]) {
c++;
} else if (c > 1) {
c--;
} else {
m = nums[i];
}
}
return m;
}