【LeetCode】007 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 major
摘要由CSDN通过智能技术生成
</pre><p></p><p>【题目】Given an array of size n, find the majority element.The majority element is the element that appears more than. You may assume that the array is non-empty and the majority element always exist in the array.给定一个大小为n的数组,找出其中出现次数超过n/2的元素。(假设其一定存在)</p><p></p><p>【解析】愚蠢如我,程序如下,不解释:</p><p></p><pre name="code" class="cpp">int majorityElement(int* nums, int numsSize) {
    int n = 0;
    for(int i = 0; i < numsSize; i++){
        for(int j = 0;j < numsSize;j++){
            if(nums[i] == nums[j])  n++;
        }
        if(n>numsSize/2)    return nums[i];
        else n = 0;
    }
}


做了一些测试,加上人脑验算了几遍,正确性应该没有问题。然而这种大量消耗时间按复杂度的程序,一律以错误论处。


6 Suggested Solutions in C++ with Explanations

这篇文章中,详细阐释了该题的6种解法,下文将以翻译为主。

文章第一句话就形容了我的算法:

Well, if you have got this problem accepted, you may have noticed that there are 7 suggested solutions for this problem. The following passage will implement 6 of themexcept the O(n^2)brute force algorithm

1. Hash Table 哈希表

哈希表解法是最直接的。我们可以从每个元素及其出现次数中获得一个

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值