leetcode 169. 多数元素

leetcode 169. 多数元素

题目详情

给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。

  • 示例 1:
    输入: [3,2,3]
    输出: 3
  • 示例 2:
    输入: [2,2,1,1,1,2,2]
    输出: 2

我的代码

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int len = nums.size();
        if ((len == 1) || (len == 2)) {
            return nums[0];
        }
        map<int, int> index;
        for (int num: nums) {
            if (index.count(num) == 0) {
                index[num] = 1;
                continue;
            }
            index[num] += 1;
        }
        for (auto iter = index.begin(); iter != index.end(); ++iter) {
            if (iter->second > len / 2) {
                return iter->first;
            }
        }
        return nums[0];
    }
};

我的成绩

执行结果:通过
执行用时 :28 ms, 在所有 C++ 提交中击败了47.36%的用户
内存消耗 :20.4 MB, 在所有 C++ 提交中击败了5.28%的用户

一些想法

  1. 本题最简单的思路莫过于先排序,然后返回处于中间的数字,但如此做下来效果并不是很理想。
  2. 改进想法是先遍历数组,然后读入map记录每个元素出现的次数,再遍历map。

执行用时为 4 ms 的范例

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

思考

可以看出,范例的想法非常巧妙,因为多数元素个数大于len / 2的性质,所以在进行记数后的数字必然是多数元素。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值