Sword refers to Offer series Sword refers to Offer 39: the number that appears more than half of the number in the array

Title description:

There is a number in the array that appears more than half the length of the array. Please find out this number.

You can assume that the array is non-empty, and there will always be a majority of elements in a given array.

Example:

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

Problem-solving ideas:

Create a new map array, then traverse the entire vector array, and then store it in the map array by key value. If the value of vextor is the same, the key of the corresponding map array is the same, then the value plus one, that is, the number plus one.

Finally, traverse the second in the map array, which is the number of each number in the vexctor.

When the second value is greater than half of the length of the vector array, it returns.

Code:

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;
    }
};

 

Guess you like

Origin blog.csdn.net/qq_46423166/article/details/110916609