[LeetCode] C++: Simple Question-Bit Operation 169. Most Elements

169. Majority Elements

Easy difficulty 863

Given an array of size  , find most of the elements in it. Most is the number of elements present in the array  is greater than the ⌊ n/2 ⌋  element.

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

 

Example 1:

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

Example 2:

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

 

Advanced:

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

1. Sort

The array given in the title, after sorting, the elements in the middle position of the array must be the most elements required

I think this question is a bit cute, hahaha!

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        return nums[nums.size()/2];
    }
};

There are many solutions to this problem, such as: brute force enumeration, hash table traversal storage, probability algorithm, divide and conquer, etc. I saw an interesting one in the official solution.

2. Moore voting

This is a solution that I saw in the official problem solution. I felt it necessary to learn and understand, so I tried it and recorded it here.

The candidate (cand_num) is initialized to nums[0], and the vote count is initialized to 1.
When encountering the same number as cand_num, the number of votes count = count + 1, otherwise the number of votes count = count-1.
When the vote count is 0, change the candidate and reset the vote count to 1.
After traversing the array, cand_num is the final answer.

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int candidate = -1;
        int count = 0;
        for (int num : nums) {
            if (num == candidate)
                ++count;
            else {
                count--;
            }
            if (count < 0) {
                candidate = num;
                count = 1;
            }
        }
        return candidate;
    }
};

 

Guess you like

Origin blog.csdn.net/weixin_44566432/article/details/113727397
Recommended