zoukankan      html  css  js  c++  java
  • LeetCode: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.

    Credits:
    Special thanks to @ts for adding this problem and creating all test cases.

    解法一:

    moore voting algorithm

    class Solution {
    public:
        int majorityElement(vector<int>& nums) {
            //moore voting algorithm
            int majority=0;
            int count=0;
            
            for(int i=0;i<nums.size();i++)
            {
                if(count==0)
                {
                    majority=nums[i];
                    count=1;
                }
                else 
                {
                    if(nums[i]==majority)
                    {
                        count++;
                    }
                    else
                    {
                        count--;
                    }
                }
            }
            return majority;
        }
    };

     解法二:hashmap实现

     1 class Solution {
     2 public:
     3     int majorityElement(vector<int>& nums) {
     4         unordered_map<int,int> mapping;
     5         
     6         for(int i=0;i<nums.size();i++)
     7         {
     8             mapping[nums[i]]++;
     9         }
    10         
    11         int target=0;
    12         int maxct=0;
    13         for(int i=0;i<nums.size();i++)
    14         {
    15             if(maxct<mapping[nums[i]])
    16                 {
    17                     target=nums[i];
    18                     maxct=mapping[nums[i]];
    19                 }
    20         }
    21         return target;
    22         
    23     }
    24 };
  • 相关阅读:
    数组(array)
    亲戚(relative)
    [ZJOI2016]小星星
    P4782 【模板】2-SAT 问题
    CF1065F Up and Down the Tree
    CF1065C Make It Equal
    CF1060F Shrinking Tree
    CF1060E Sergey and Subway(点分治)
    CF1060D Social Circles
    CF1060C Maximum Subrectangle
  • 原文地址:https://www.cnblogs.com/xiaoying1245970347/p/4728419.html
Copyright © 2011-2022 走看看