#46 Majority Number

本文介绍了一种寻找数组中出现次数超过一半的多数元素的有效方法。通过使用map记录每个元素出现的频率,可以在O(n)时间内找到多数元素,并且仅使用O(1)额外空间。

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

题目描述:

Given an array of integers, the majority number is the number that occurs more than half of the size of the array. Find it.

Example

Given [1, 1, 1, 1, 2, 2, 2], return 1

Challenge 

O(n) time and O(1) extra space

题目思路:

这题可以用greedy方法做,不过greedy的方法没什么可学习性。这里还是用了普通的方法,建一个map记录每个数出现的次数这么做。

Mycode(AC = 29ms):

class Solution {
public:
    /**
     * @param nums: A list of integers
     * @return: The majority number
     */
    int majorityNumber(vector<int> nums) {
        // write your code here
        if (nums.size() == 0) return 0;
        
        // use map to record the number of times that
        // nums[i] appears
        map<int, int> helper;
        for (int i = 0; i < nums.size(); i++) {
            if (helper.find(nums[i]) != helper.end()) {
                helper[nums[i]]++;
                if (helper[nums[i]] > nums.size() / 2) {
                    return nums[i];
                }
            }
            else {
                helper[nums[i]] = 1;
            }
        }
        
        for (auto it = helper.begin(); it != helper.end(); it++) {
            if (it->second > nums.size() / 2) {
                return it->first;
            }
        }
        
        return 0;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值