169. Majority Element

1.描述

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.
Credits:Special thanks to @ts for adding this problem and creating all test cases.

2.分析

3.代码

int majorityElement(int* nums, int numsSize) {
    if (NULL == nums || numsSize <= 0 ) exit(-1);
    int majority = nums[0];
    unsigned int count = 1;
    for (unsigned int i = 1; i < numsSize; ++i) {
        if (count == 0) {
            majority = nums[i];
            ++count;
        } else {
            count += majority == nums[i] ? 1 : -1;
        }
    }
    return majority;
}

4.其他方法

利用快速排序的思想,每次确定一个数的位置,数组的中位数就是出现次数最多的数。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容