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.
一刷
題解:
由于appears more than ? n/2 ? times, 用count變量計算當前值出現(xiàn)次數(shù),如果如果num[I]與當前值不等,count--, 如果count小于0,改變當前值,count歸零。
public class Solution {
public int majorityElement(int[] nums) {
int major = nums[0], count = 1;
for(int i=1; i<nums.length; i++){
if(count == 0){
count++;
major = nums[i];
}
else if(major == nums[i]) count++;
else count--;
}
return major;
}
}