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
Method 1:
very tricky method, since we know if the array is sorted, then the number at nums[nums.length/2] position is for sure, the majority number.
java code:
public static int majorityElement(int[] nums){
Arrays.sort(nums);
return nums[nums.length/2];
}
but this is a less general method and I don't expect to memorize.
Method 2:
another easy-to-understand method is the vote algorithm, where we maintain a counter starting with 0
we initially see the first element as the potential majority number.
we go through the nums[] and every time we see the potential majority we make counter+1 else counter-1.
and if the counter ends with 0 then it means the former part of array has same number of potential number and non-potential number.
we "forget" this part and move on, and eventually get a remaining number.
java code:
public static int majorityElement(int[] nums){
int counter = 0;
Integer potential = null;
// only with <Integer> type can we assign this null value
for(int i:nums){
if(counter == 0){
//forget former part
potential = i;
}
counter += (i==potential) ? 1 : -1;
}
return potential;
}