【LeetCode】007 Majority Element 少数服从多数

本文介绍了LeetCode 007题目的六种解法,包括哈希表、排序、随机法、分治、摩尔投票算法和位操作。哈希表直接统计出现次数,排序后取中间元素,随机法快速得出结果,分治法递归思考,摩尔投票算法高效遍历,位操作利用二进制特性解决问题。这些方法在C++中实现,并讨论了其时间复杂度和效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

</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. H

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值