Sword Finger Offer Interview Question 39. Numbers with more than half of the occurrences in the array [Simple]

My solution:

1. Use unordered_map to record the number of occurrences of each value, and return this number when it is equal to half of the array

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int mid=(nums.size()+1)/2;
        unordered_map<int,int> m;
        for(int c:nums){
            if(m.count(c)){
                m[c]++;
                if(m[c]>=mid)   return c;
            }
            else{
                m[c]=1;
                if(m[c]>=mid)   return c;
            }
        }
        return 0;
    }
};

2. Because the number of times is the last, he has more times than all the numbers added together

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int count=0;
        int res;
        for(int c:nums){
            if(count==0){    res=c;
            count=1;
            }
            else{
                if(res==c)  count++;
                else    count--;
            }
        }
        return res;
    }
};

Published 65 original articles · Like1 · Visits 481

Guess you like

Origin blog.csdn.net/qq_41041762/article/details/105479554