数组中元素出现次数相关问题 Majority Element

共两道:
1、数组中,出现次数超过一半的元素(一定存在):LeetCode - 169. Majority Element
2、数组中,出现次数超过 n / 3 的元素(不一定存在):LeetCode - 229. Majority Element II

一、LeetCode - 169. 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.

Input: [3,2,3] Output: 3
Input: [2,2,1,1,1,2,2] Output: 2

  很简单,就是既然一个数出现次数超过数组长度的一半,比如这个数是 a,那就相当于用一个 a 去和一个不是 a 的数抵消,最后数组肯定还剩 >= 1 个 a,代码如下(O(N)):

int majorityElement(vector<int>& nums) {
    int cur = nums[0], cur_cnt = 1;
    for(int i = 1; i < nums.size(); ++i)
        if(nums[i] != cur){
            if(cur_cnt == 1) cur = nums[i];
            else             --cur_cnt;
        }
        else 
            ++cur_cnt;
    return cur;
}
二、LeetCode - 229. Majority Element II

Given an integer array of size n, find all elements that appear more than ⌊ n / 3 ⌋ times.
Note: The algorithm should run in linear time and in O(1) space.

Input: [3,2,3] Output: [3]
Input: [1,1,1,3,3,2,2,2] Output: [1,2]

  ⌊ n / 3 ⌋ 是下取整,用 C++ 的 / 就可以了。和上边的题一样,我们先认为这两个数存在(如果存在,最多存在两个),然后取到最后存活下来的两个数,但是由于不一定存在,所以还需要在遍历一次检查是否确实超过了 n / 3,代码如下(O(N) time, O(1) space):

vector<int> majorityElement(vector<int>& nums) {
    const int len = nums.size();
    int a = INT_MIN, a_cnt = 0, b = INT_MIN, b_cnt = 0;
    for(const int& n : nums) {
        if(n == a)
            ++a_cnt;
        else if(n == b)
            ++b_cnt;
        else if(a_cnt == 0) {
            a_cnt = 1;
            a = n;
        }
        else if(b_cnt == 0) {
            b_cnt = 1;
            b = n;
        }
        else {
            --a_cnt;
            --b_cnt;
        }
    }
    a_cnt = 0, b_cnt = 0;
    for(const int& n : nums) {
        if(n == a)      ++a_cnt;
        else if(n == b) ++b_cnt;
    }
    vector<int> res;
    if(a_cnt > len / 3) res.push_back(a);
    if(b_cnt > len / 3) res.push_back(b);
    return res;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值