当前位置: 首页 > 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/

http://www.dtcms.com/a/3188.html

相关文章:

  • 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
  • Postman如何做接口自动化测试?
  • java.sql.SQLException: ORA-28000: the account is locked
  • C#8.0本质论第十章--合式类型
  • 【MySQL索引与优化篇】InnoDB数据存储结构
  • 【JavaScript】快速学习JS
  • 聊聊“JVM 调优JVM 性能优化”是怎么个事?
  • Transit path
  • javaswing/gui+mysql的学生信息管理系统
  • 代码随想录 | Day61 and 62
  • 77 全排列