this is a question from leetcode:
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.
If you want to get the best solution, then you must analyst and make use of all the information provided in the problem.
question analysis:
the key hint is that the majority element always exist. So that means that the count of majority element is great than the count of all other element, so the
count(majority) - count(others) > 0.
below is the best solution:
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.
If you want to get the best solution, then you must analyst and make use of all the information provided in the problem.
question analysis:
the key hint is that the majority element always exist. So that means that the count of majority element is great than the count of all other element, so the
count(majority) - count(others) > 0.
below is the best solution:
public int majorityElement(int[] nums) {
int result = nums[0];
int count = 1;
for(int i = 1; i < nums.length; i++){
if(result == nums[i]){
count++;
}else{
count--;
}
if(count == 0){
result = nums[i];
count++;
}
}
return result;
}