leetcode 169. Majority Element
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.
AC:
int compare(const void *a,const void *b)
{
return *(int *)a-*(int *)b;
}
int majorityElement(int* nums, int numsSize) {
qsort(nums,numsSize,sizeof(nums[0]),compare);
int k=numsSize/2+1;
int i;
for(i=0;i<=numsSize-k;i++)
{
int buf=nums[i];
int j;
for(j=1;j<k;j++)
{
if(buf!=nums[j])
{
break;
}
}
if(j==k)
{
return buf;
}
}
return nums[i];
}
tips:快速排序拍好后,然后判断前一半的数中,哪个数及其后连续一半数组长度的数是相同的,则返回该数。