当前位置: 首页 > news >正文

leetCode 229. 多数元素 II + 摩尔投票法 + 进阶 + 优化空间

229. 多数元素 II - 力扣(LeetCode)


给定一个大小为 的整数数组,找出其中所有出现超过 ⌊ n/3 ⌋ 次的元素。

进阶:尝试设计时间复杂度为 O(n)、空间复杂度为 O(1)的算法解决此问题。 


(1)哈希表

class Solution {
public:
    // 哈希
    vector<int> majorityElement(vector<int>& nums) {
        unordered_map<int,int> mp;
        for(const int& a:nums) mp[a]++;
        int n = nums.size() / 3;
        int i=0;
        vector<int> ans;
        for(auto &it:mp) {
            if(it.second > n) ans.push_back(it.first); 
        }
        return ans;
    }
};

(2) 摩尔投票法

class Solution {
public:
    // 摩尔投票法
    vector<int> majorityElement(vector<int>& nums) {
        // 创建返回值
        vector<int> res;
        if (nums.empty() || nums.size() == 0) return res;
        // 初始化两个候选人candidate,和他们的计票
        int cand1 = nums[0],count1 = 0;
        int cand2 = nums[0],count2 = 0;

        // 摩尔投票法,分为两个阶段:配对阶段 和 计数阶段
        // (1) 配对阶段
        for(const int &num : nums) {
            // 投票
            if(cand1 == num) {count1++;continue;}
            if(cand2 == num) {count2++;continue;}

            // 第 1 个候选人配对
            if(count1 == 0) {
                cand1 = num;
                count1++;
                continue;
            }

            // 第 2 个候选人配对
            if(count2 == 0) {
                cand2 = num;
                count2++;
                continue;
            }

            count1--;
            count2--;
        }

        // (2)计数阶段 : 找到了两个候选人之后,需要确定票数是否满足大于 N/3
        count1=0;
        count2=0;
        for(const int &num : nums) {
            if (cand1 == num) count1++;
            else if (cand2 == num) count2++;
        }

        if (count1 > nums.size() / 3) res.push_back(cand1);
        if (count2 > nums.size() / 3) res.push_back(cand2);
        return res;
    }
};

推荐和参考文章:

229. 多数元素 II - 力扣(LeetCode)icon-default.png?t=N7T8https://leetcode.cn/problems/majority-element-ii/solutions/123170/liang-fu-dong-hua-yan-shi-mo-er-tou-piao-fa-zui-zh/229. 多数元素 II - 力扣(LeetCode)icon-default.png?t=N7T8https://leetcode.cn/problems/majority-element-ii/solutions/1060343/gong-shui-san-xie-noxiang-xin-ke-xue-xi-ws0rj/

相关文章:

  • yo!这里是进程间通信
  • 苍穹外卖-01
  • Linux Ubunto Nginx安装
  • vscode中如何将cmd设置为默认终端
  • 使用Spring Data Elasticsearch 进行索引的增、删、改、查
  • 【计算机网络】(谢希仁第八版)第一章课后习题答案
  • Win10中Pro/E鼠标滚轮不能缩放该怎么办?
  • RabbitMQ原理(五):消费者的可靠性
  • MIT Kimera-VIO-ROS 安装
  • rm -rf,删了文件空间却没释放?
  • java - IDEA IDE - 设置字符串断点
  • vue笔记(三)
  • 48.Redis缓存设计与性能优化
  • 『第十章』仪态万千的雨燕:UIKit 和 SwiftUI
  • 1819_ChibiOS的互斥信号与条件变量
  • Ant Design Vue UI框架的基础使用,及通用后台管理模板的小demo【简单】
  • 数据结构|基础知识定义
  • Linux系统下配置王爽汇编语言环境
  • 使用了百度OCR,记录一下
  • node.js - 上传文件至阿里云oss
  • 热点问答|澳大利亚联邦选举结果有何看点
  • 亚马逊一季度利润增超六成:云业务增速放缓,警告关税政策或影响业绩指引
  • A股三大股指涨跌互现:3343股收涨,两市成交超1.1万亿元
  • 许峰已任江苏省南京市副市长
  • 如何反击右翼思潮、弥合社会分裂:加拿大大选镜鉴
  • 在循环往复的拍摄中,重新发现世界