[剑指 offer] JT28---numbers that appear more than half of the number of times in the array (use a hash table to support the edge!)

Sword Finger Offer 28th Question

The topic is as follows

Insert picture description here

Idea and code

The rare sand sculpture questions in the sword finger offer are
all written down how many times there are, and then check if it is more than half of the time, and output directly. The
hash table helps you double the search speed, which is really cool!

#include<unordered_map>
class Solution {
    
    
public:
    int MoreThanHalfNum_Solution(vector<int> numbers) {
    
    
        unordered_map<int,int> count;
        for(int i=0;i<numbers.size();i++){
    
    
            if(!count.count(numbers[i]))
                count[numbers[i]]=1;
            else
                count[numbers[i]]++;
        }
        for(unordered_map<int,int>::iterator it=count.begin();it!=count.end();it++){
    
    
            if(it->second>numbers.size()/2)
                return it->first;
        }
        return 0;
    }
};

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_42136832/article/details/114847291