【leetcode】多数元素

 

复制代码
int majorityElement(int* nums, int numsSize){
    int key = nums[0];
    int count = 0;
    for (size_t i = 0; i < numsSize; i++)
    {
        if(nums[i] == key)
            count++;
        else
            count--;
        
        if(count <= 0)
        {
            key = nums[i+1];
        }
        
    }
    return key;
}
复制代码

 

int cmp(const void* a, const void* b){
    return *(int*)a - *(int*)b;
}
int majorityElement(int* nums, int numsSize){
    qsort(nums,numsSize,sizeof(int),cmp);
    return nums[numsSize/2];
}

 

posted @   温暖了寂寞  阅读(82)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示