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;
        }
    };
  • 相关阅读:
    Unity3D在各平台上的路径
    Unity简单的单例模式
    C#遍历枚举(Enum)
    C#常用的流类型(FileStream,SteamWriter/StreamReader,MemoryStream等)
    编写一个C程序,运行时输入a,b,c三个值,输出其中最大者
    精确一维搜索算法(直接法)
    Java一维数组求和
    java 导出EXCEL
    Java判断字符串的数字类型(小数、整数)
    网址存储
  • 原文地址:https://www.cnblogs.com/Atanisi/p/6803708.html
Copyright © 2011-2022 走看看