Majority Element

本文介绍了一种简单的方法来找到数组中出现次数超过一半的元素,通过设置计数器和索引来实现。此方法适用于非空数组且已知存在多数元素的情况。

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

问题描述:

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.

解决思路:这是一个求解数组主元素的题目,数组的主元素是指数组中出现次数超过一半的元素。此题是假设数组非空并且主元素存在,所以比较简单。主元素总会比其他元素多,我们设置两个变量maj_index用于记录主元素的位置,count用于记录主元素出现的次数,然后一次比较数组元素,如果相同则count加1,不同则减1,若count为零,则替换maj_index,并将count置为1.


C++:

class Solution {
public:
    int majorityElement(vector<int> &num) {
        int maj_index,count;
        maj_index = 0;
        count = 1;
        for(int i =1; i < num.size(); i++){
            if (num[i] == num[maj_index])
                count ++;
            else
                count --;
            if (count == 0){
                maj_index = i;
                count = 1;
            }
        }
        return num[maj_index];
    }
};
python:

class Solution:
    # @param num, a list of integers
    # @return an integer
    def majorityElement(self, num):
        maj_index = 0
        count = 1
        for i in range(1,len(num)):
            if num[i] == num[maj_index]:
                count += 1
            else:
                count -= 1
            if count == 0:
                maj_index = i
                count = 1
        return num[maj_index]

延伸阅读:http://www.geeksforgeeks.org/majority-element/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

godleft90

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值