• 229. Majority Element II My Submissions Question


    Total Accepted: 23103 Total Submissions: 91679 Difficulty: Medium

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

    Hint:

    How many majority elements could it possibly have?
    Do you have a better hint? Suggest it!

    最多只有两个候选数字。要求O(1)空间,可以分别用两个变量保存候选数字和计数,方法大致和169. Majority Element My Submissions Question
    相同。代码如下:

    vector<int> majorityElement(vector<int>& nums) {
        vector<int> res;
        if (nums.empty())
            return res;
            
        int cand1 = nums[0], cand2 = 0;
        int count1 = 1, count2 = 0;
        
        for (int i = 1; i < nums.size(); ++i) {   
            if (cand1 == nums[i]) {
                ++count1;
            }
            else if (cand2 == nums[i]) {
                ++count2;
            }
            else if (count1 == 0) {
                cand1 = nums[i];
                ++count1;
            }
            else if (count2 == 0) {
                cand2 = nums[i];
                ++count2;
            }     
            else {
                --count1;
                --count2;
            }
        }
    
        //判断候选是否满足条件
        count1 = count2 = 0;
        for (int i = 0; i < nums.size(); ++i) {
            if (cand1 == nums[i])
                ++count1;
            else if (cand2 == nums[i])
                ++count2;
        }
        if (count1 > nums.size() / 3)
            res.push_back(cand1);
        if (count2 > nums.size() / 3)
            res.push_back(cand2);
    
        return res;
    }
  • 相关阅读:
    python库--pandas--文本文件读取
    python库--flashtext--大规模数据清洗利器
    PyCharm--帮助文档
    Git--命令
    symfony doctrine generate entity repository
    [转]MySQL性能优化的最佳20+条经验
    svn使用
    一致性hash
    JavaScript学习笔记 1
    curl发出请求
  • 原文地址:https://www.cnblogs.com/gr-nick/p/5222595.html
Copyright © 2020-2023  润新知