zoukankan      html  css  js  c++  java
  • 38- Majority Element

    1. Majority Element My Submissions QuestionEditorial Solution
      Total Accepted: 110538 Total Submissions: 268290 Difficulty: Easy
      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.

    Subscribe to see which companies asked this question

    思路:so easy

    class Solution {
    public:
        int majorityElement(vector<int>& nums) {
            map<int,int> m;
            int n=nums.size();
            if(n==1)return nums[0]; 
            for(int i=0;i<nums.size();++i){
                if(m.count(nums[i])){
                    m[nums[i]]++;
                    if(m[nums[i]]>nums.size()/2)return nums[i];
                }
                else m[nums[i]]=1;
            }
        }
    };
  • 相关阅读:
    Kattis
    Kattis
    Kattis
    Kattis -Backspace
    Kattis
    Kattis
    Kattis
    Hihocoder1061-Beautiful String
    Hihocoder1350-Binary Watch
    Hihocoder1458-Parentheses Matching(stack,vector)
  • 原文地址:https://www.cnblogs.com/freeopen/p/5482931.html
Copyright © 2011-2022 走看看