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.
Analysis:
There are many methods for this question.
1 HashTable
2 Vote method.
3 Bit manipulation;
vote method code
public class Solution {
public int majorityElement(int[] nums) {
int length = nums.length;
if(length == 1)
return nums[0];
int tem = nums[0];
int number = 1;
for(int i = 1; i < length;i++){
if(nums[i] != tem)
{
if(number == 1){
tem = nums[i];
number = 1;
}
else{
number--;
}
}
else{
number++;
}
}
return tem;
}
}
3 Bit manipulation method: just to count the number of 1 bit for every position: if the number of 1 for specific position is larger than numberOfArray/2, it must belongs to the majority number