Leetcode: [169. Most elements]

topic

 Given an  n array  of size nums , return the majority of its elements. The majority element refers to the elements that appear more than  once in the array  ⌊ n/2 ⌋ .

You can assume that arrays are non-empty and that there is always a majority of elements in a given array.

Difficulty: Easy

Topic link: 169. Most elements

Example 1:

Input: nums = [3,2,3]
 Output: 3

Example 2:

Input: nums = [2,2,1,1,1,2,2]
 Output: 2

hint:

  • n == nums.length
  • 1 <= n <= 5 * 104
  • -109 <= nums[i] <= 109

Advanced: Try to design an algorithm with time complexity of O(n) and space complexity of O(1) to solve this problem.

Code display

int majorityElement(int* nums, int numsSize){
    int king = nums[0];//假设第一个是多数元素
    int votes = 1;
    int i = 0;
    for( i = 0;i<numsSize;i++)
    {
        if(nums[i] == king)
            votes++;
        else
        {
            votes--;
            if(votes == 0)
            {
                king = nums[i];//多数元素
                votes = 1;//票数重置
            }
        }
    }
    return king;
}

 【Analysis】

The advanced approach adopted here (time complexity is O(n), space complexity is O(1))

Moore voting

A Brief Introduction to Moore Voting

Moore's voting method:

The core is fighting consumption.

Playing a game of war between princes, assume that your population exceeds half of the total population, and you can ensure that everyone in the population will die together one-on-one when they go to war. The country that still has people alive in the end wins.

Then there will be a big melee. At worst, everyone will unite against you (corresponding to the number you choose as the counter every time is the mode), or other countries will attack each other (other numbers will be chosen as the counter number), but As long as you don't fight among yourself, you will definitely win in the end.

The last thing left must be our own people

In fact, the elements in the nums array can be distinguished between friendly forces (same elements) and enemy forces (different elements). If the same element is encountered, add 1, and if the element is not used, decrement 1.

Guess you like

Origin blog.csdn.net/qq_72505850/article/details/132507655