剑指Offer 系列 剑指 Offer 39:数组中出现次数超过一半的数字

题目描述:

数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。

你可以假设数组是非空的,并且给定的数组总是存在多数元素。

示例 :

输入: [1, 2, 3, 2, 2, 2, 5, 4, 2]
输出: 2

解题思路:

新建一个map数组,然后遍历整个vector数组,然后通过键值的方式存到map数组中,如果vextor的值相同,则对应map数组的键相同,则值加一,即数量加一。

最后再遍历map数组中的second,即vexctor中每个数的数量。

当该second值大于vector数组的长度的一半时,则返回。

代码:

class Solution {
public:
    int majorityElement(vector<int>& nums) {
         map<int,int> q;
        for(auto x:nums)
        {
            q[x]++;
        }
        for(auto y:q)
        {
            if(y.second > nums.size()/2)
            return y.first;
        }
        return 0;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_46423166/article/details/110916609