LIUPENG BLOG
Liupeng
Jun 5, 2020
It takes 1 minutes to read this article.

主要元素

题目

截屏2020-06-05 下午11.55.56

题解

int MainElement::majorityElement(std::vector<int> &nums) {
    std::map<int, int> myMap;
    for (auto item : nums) {
        std::map<int ,int>::iterator temp;
        temp = myMap.find(item);
        if(temp == myMap.end()) myMap[item] = 1;
        else myMap[item] = myMap[item] + 1;
    }
    std::map<int, int>::iterator temp;
    int p = 0, index = -1;
    for (temp = myMap.begin(); temp != myMap.end(); temp++) {
        if (temp->second > p) index= temp->first, p = temp->second;
    }
    //std::cout << p << std::endl;
    if (p * 2 <= nums.size()) index = -1;
    return index;
}

结果

截屏2020-06-05 下午11.54.56