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.
Example 1:
Input: [3,2,3]
Output: 3
Example 2:
Input: [2,2,1,1,1,2,2]
Output: 2
题意:寻找主数,主数就是一个数组中个数大于n/2的数,题目默认数组一定存在主数
思路:既然主数个数大于n/2,则不管以怎样的顺序排列,主数的个数都可以抵消掉其他数。所以先设第一个数是主数,用count记录当前主数的相差数,如果后面那个数与主数相等,count+1,不等count-1。当count<=0时,更换当前值为主数
class Solution {
public int majorityElement(int[] nums) {
int len = nums.length;
int count = 1;//默认第一个数为主数,相差数为1
int main = nums[0];
for(int i=1;i<len;i++){//从数组第二位开始循环判断
if(nums[i] == main) {//如果当前数等于主数
count++;
}else{//如果当前数不等于主数
if(count>0){//并且相差数>0,即主数的次数没有被抵消完
count--;
}else{//不等并且相差数<=0,主数次数已经被抵消完
main = nums[i];//重新设置主数
count = 1;//主数相差数为1
}
}
}
return main;
}
}