Majority Element题目介绍:
给定一个长度为n的数组的时候,找出其中的主元素,即该元素在数组中出现的次数大于n/2的取整。
思路
如果把众数记为 +1,把其他数记为 -1,将它们全部加起来,显然和大于 0,从结果本身可以看出众数比其他数多。
算法
class Solution {
public int majorityElement(int[] nums) {
int count = 0;
Integer candidate = null;
for(int n : nums){
if(count == 0){
candidate = n;
//保证count永远非负。
//因为众数大于数组长度的一半,遍历完数组,
//candidate必为所求
}
count += (n==candidate) ? 1 : -1;
}
return candidate;
}
}