思路:Boyer-Moore 投票算法
——时间复杂度:O(n)。Boyer-Moore 算法只对数组进行了一次遍历
——空间复杂度:O(1)。Boyer-Moore 算法只需要常数级别的额外空间
class Solution {
public int majorityElement(int[] nums) {
int count = 0;
Integer candidate = null;
for (int num : nums) {
if (count == 0) {
candidate = num;
}
count += (num == candidate) ? 1 : -1;
}
return candidate;
}
}
Boyer-Moore 投票算法参考:https://blog.csdn.net/kimixuchen/article/details/52787307