zoukankan      html  css  js  c++  java
  • 169. Majority Element

    Problem statement:

    Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

    You may assume that the array is non-empty and the majority element always exist in the array.

    Solution one: sorting(AC)

    The number of majority elements is greater than n/2. It must take n/2 if we sort the array no matter by ascending or descending order.

    Time complexity is O(nlgn). 

    class Solution {
    public:
        int majorityElement(vector<int>& nums) {
            sort(nums.begin(), nums.end());
            return nums[nums.size() /2];
        }
    };

    Solution two: hash table(AC)

    We can employ a hash table indexed by the element, corresponding to the number of the element.

    loop from the beginning to end, Once the number of an element is greater than n / 2, return the element.

    The worst case of time complexity is O(n), generally, it is less than O(n). 

    The worst case of space complexity is O(n), generally is less than O(n).

    class Solution {
    public:
        int majorityElement(vector<int>& nums) {
            int size = nums.size();
            unordered_map<int, int> table;
            for(auto num : nums){
                if((++table[num]) > size / 2){
                    return num;    
                }
            }
            return -1;
        }
    };

    Solution three: Boyer-Moore majority vote system(AC)

    We implement the Boyer-Moore majority vote system, using the philosophy of counteracting. 

    One variable, candidate, represents the candidate, one, cnt,  represents the number of the candidate.

    • If count == 0; candidate = num;
    • else if candidate = num ---> count++;
    • else if candidate != num ---> count--;

    Time complexity is O(n). Space complexity is O(1).

    class Solution {
    public:
        int majorityElement(vector<int>& nums) {
            int candidate = 0;
            int cnt = 0;
            for(auto num : nums){
                if(cnt == 0){
                    candidate = num;
                    cnt++;
                } else if (candidate == num) {
                    cnt++;
                } else {
                    cnt--;
                }
            }
            return candidate;
        }
    };
  • 相关阅读:
    JavaScript面向对象之闭包的理解
    JavaScript面向对象之函数构造器的理解
    记录jq控制select 选中状态
    JavaScript面向对象之创建类和方法
    获取对象属相 点运算符 和方括号 运算符
    parseFloat 和 Number isNaN 转换
    Js数据类型和运算符
    break , continue 和 标签 跳出循环
    javaScript--循环语句
    三元运算符
  • 原文地址:https://www.cnblogs.com/wdw828/p/6911211.html
Copyright © 2011-2022 走看看