• Majority Element


    题目链接https://leetcode.com/problems/majority-element/

    这道题最一开始的思路是建立一个hashmap,这样就是 O(n) time和 O(n) space。

    但是后来看了一下leetcode给出的官方解答,发现moore voting algorithm很有意思,就记了下来,以后遇到这个问题就用他这个方法了。

    以下摘自leetcode

    Runtime: O(n) — Moore voting algorithm: We maintain a current candidate and a counter initialized to 0. As we iterate the array, we look at the current element x:

    1. If the counter is 0, we set the current candidate to x and the counter to 1.

      2. If the counter is not 0, we increment or decrement the counter based on whether x is the current candidate.

    After one pass, the current candidate is the majority element. Runtime complexity = O(n).

    博主的code

    class Solution {
    public:
        int majorityElement(vector<int> &num) {
            int candidate = num[0];
            int counter = 0;
            for(int i = 0; i < num.size(); i++) {
                if(counter == 0) {
                    candidate = num[i];
                    counter = 1;
                }
                if(candidate == num[i])
                    counter++;
                else
                    counter--;
            }
            return candidate;
        }
    };

    至于这个算法为什么是正确的,证明在发明者的这篇paper中 http://www.cs.rug.nl/~wim/pub/whh348.pdf

  • 相关阅读:
    列表、元组、字符串的相互转化
    python中的常用BIF
    python中的类型
    python内置模块
    打印字体颜色整理
    xml操作
    内置函数
    迭代器
    装饰器
    函数
  • 原文地址:https://www.cnblogs.com/walcottking/p/4430863.html
Copyright © 2020-2023  润新知