《leetCode》:Majority Element

来源:互联网 发布:富春江知乎 编辑:程序博客网 时间:2024/06/05 03:04

题目

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.

思路

先排序,取中间的即可。
更多的思路可以看这篇博文:http://blog.csdn.net/u010412719/article/details/49047033

int cmp(const void *a,const void *b){    return  ((*(int*)a)-(*(int*)b));}int majorityElement(int* nums, int numsSize) {    if(nums==NULL||numsSize<1){        return 0;    }    qsort(nums,numsSize,sizeof(nums[0]),cmp);    return nums[numsSize/2];}
1 0