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.
public class Solution {
public int majorityElement(int[] nums) {
Arrays.sort(nums);
int i=0;
int count=1;
int len=nums.length;
if(len<3) return nums[0];
int compare=len>>1;
while(i<len-1)
{
if(nums[i]==nums[i+1])
{
count+=1;
i+=1;
if(count>compare) return nums[i];
}
else
{
count=1;
i+=1;
}
}
return 0;
}
}