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

    题目:

    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 1 ()

    class Solution {
    public:
        int majorityElement(vector<int>& nums) {
            int n = nums.size();
            int cnt = 0, majority = 0;
            for(auto n : nums) {
                if(majority == n) cnt++;
                else {
                    cnt--;
                    if(cnt <= 0) {
                        cnt = 1;
                        majority = n;
                    } 
                }
            }
            return majority;    
        }
    };

    Solution 2 ()

    class Solution {
    public:
        int majorityElement(vector<int>& nums) {
            unordered_map<int, int> counts; 
            int n = nums.size();
            for (int i = 0; i < n; i++)
                if (++counts[nums[i]] > n / 2)
                    return nums[i];
            
        }
    };

    Solution 3 ()

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

    Solution 4 ()

    class Solution {
    public:
        int majorityElement(vector<int>& nums) {
            int ret = 0;
            for(int i=0; i<32; ++i) {
                int ones = 0, zeros = 0;
                for(int j=0; j<nums.size(); ++j) {
                    if((nums[j] & (1<<i)) != 0) ++ones;
                    else ++zeros;
                }
                if(ones > zeros) ret |= (1<<i);
            }   
            return ret;
        }
    };

    Solution 5 ()

    class Solution {
    public:
        int majorityElement(vector<int> nums) {
            int n = nums.size();
            if(n <= 1) return nums[0];
            int m1 = majorityElement(vector<int> (nums.begin(), nums.begin() + n/2));
            int m2 = majorityElement(vector<int> (nums.begin() + n/2, nums.end()));
            if(m1 == m2) return m1;
            int cnt = 0;
            for(auto num:nums) {
                if(num == m1) cnt++;
                if(cnt > n/2) return m1;
            }
            return m2;
        }
    };
  • 相关阅读:
    产品经理之职责篇
    Scrum实践
    通用泛型存储接口的设计
    Jquery ajax执行顺序 返回自定义错误信息
    Js参数值中含有单引号或双引号解决办法
    Winform下的HTMLEditor引用Microsoft.mshtml的注意事项
    引用类型传参不加 ref 的注意事项
    List<T> 排序(Sort)查找(Find)功能的多种实现
    多线程三种传值方式
    SQL 存储过程传入多个ID
  • 原文地址:https://www.cnblogs.com/Atanisi/p/6803708.html
Copyright © 2011-2022 走看看