【LeetCode-数组】求众数 II

2021-02-02 01:17

阅读:665

标签:说明   logs   示例   时间复杂度   不能   problem   题目   描述   for   

题目描述

给定一个大小为 n 的数组,找出其中所有出现超过 ? n/3 ? 次的元素。
说明: 要求算法的时间复杂度为 O(n),空间复杂度为 O(1)。
示例:

输入: [3,2,3]
输出: [3]

输入: [1,1,1,3,3,2,2,2]
输出: [1,2]

题目链接: https://leetcode-cn.com/problems/majority-element-ii/
做这题之前要先做一下多数元素。

思路

要求算法的时间复杂度为 O(n),空间复杂度为 O(1),所以排序和哈希表的算法都不能用了。这题使用和多数元素类似的投票法。
超过n/3的元素一定不超过2个。我们将这两个数字记为candi1和candi2,对应的票数分别为cnt1和cnt2。算法如下:

  • candi1、candi2、cnt1、cnt2均初始化为0;
  • 遍历数组:
    • 如果cnt1==0,则将数组当前值赋值为candi1,cnt1++;
    • 否则,如果当前值等于candi1,cnt1++;
    • 如果cnt2==0,则将数组当前值赋值为candi2,cnt2++;
    • 否则,如果当前值等于candi2, cnt2++;
    • 如果cnt1,cnt2均不为0,且当前值和candi1,candi2都不相等,则cnt1--, cnt2--;
  • 循环结束后,再遍历数组一遍,判断candi1,candi2出现次数是否超过了n/3.

代码如下:

class Solution {
public:
    vector majorityElement(vector& nums) {
        if(nums.empty()) return {};

        int candi1=0, candi2=0;
        int cnt1=0, cnt2 = 0;

        for(int i=0; i ans;
        if(cnt1>nums.size()/3) ans.push_back(candi1);
        if(cnt2>nums.size()/3) ans.push_back(candi2);
        return ans;
    }
};
  • 时间复杂度:O(n)
  • 空间复杂度:O(1)

参考

1、https://leetcode-cn.com/problems/majority-element-ii/solution/169ti-sheng-ji-ban-xiang-jie-zhu-xing-jie-shi-tong/

【LeetCode-数组】求众数 II

标签:说明   logs   示例   时间复杂度   不能   problem   题目   描述   for   

原文地址:https://www.cnblogs.com/flix/p/12812160.html


评论


亲,登录后才可以留言!