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.
输入一个数组,找到其中的主要元素(主要元素的个数大于n/2向下取整)。
思路①将数组排序后,位于n/2向下取整位置的即为主要元素。
int majorityElement(vector<int>& nums) {
sort(nums.begin(),nums.end());
return nums[nums.size()/2];
}
思路②Moore's voting algorithm: 不断删去数组中两个不同的数,直到最后剩下的数都相同,即为主要元素。
public int majorityElement(int[] num) {
int major=num[0], count = 1;
for(int i=1; i<num.length;i++){
if(count==0){
count++;
major=num[i];
}else if(major==num[i]){
count++;
}else count--;
}
return major;
}