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.
思路:之前写了一遍,然后因为敏感词被封了.....不敢多写了,方法是摩/尔/投/票/法,自己百度吧,我都不知道哪个词敏感....
class Solution {
public int majorityElement(int[] nums) {
int count = 1;
int majority = nums[0];
for(int i = 1;i<nums.length;i++){
if(nums[i]!=majority){
count--;
if(count<=0){
majority = nums[i];
count = 1;
}
}else{
count++;
}
}
return majority;
}
}