Given an array of sizen, find the majority element. The majority element is the element that appearsmore than⌊ n/2 ⌋
times.
You may assume that the array is non-empty and the majority element always exist in the array.
Credits:
Special thanks to@tsfor adding this problem and creating all test cases.
class Solution {
public int majorityElement(int[] nums) {
int count = 0, ans = 0;
for (int num : nums){
if (count == 0){
ans = num;
count++;
}
else if (num != ans){
count--;
}
else{
count++;
}
}
return ans;
}
}