Voting method

Title description:

Given an array of size n, find most of the elements. Most elements refer to elements that occur more than ⌊ n / 2 ⌋ in the array.

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

Of course: Hash method, sort and then take the middle +1 number. It's very simple, but it's not as
efficient as the voting method ~

Let's take a look at the voting method

class Solution {
public:

//投票法  时间复杂度O(N )  空间O(1)
    int majorityElement(vector<int>& nums) {
        int candidate = -1;//候选数
        int count =0;//票数
        for(auto num : nums)
        {
            if(num == candidate)
            {
                ++count;//票数+1
            }
            else 
            {
                --count;//候选数投票相对少1 
                if(count < 0)
                {
                    candidate = num;//更新候选数
                    count =1;
                }
            }
        }
        return candidate;
    }
};
Published 109 original articles · Like 44 · Visits 30,000+

Guess you like

Origin blog.csdn.net/weixin_44030580/article/details/105429887