Jianzhi offer 39 There are more than normal numbers in the array (Moore voting method)

Moore voting method, problem-solving ideas

Three common solutions to this question:
1. Hash table
2. Array sorting method
3. Moore voting method

Moore voting

设输入数组nums的众数为&x&,数组长度为$n$.

Inference 1: If the number of votes for the majority number is +1, and the number of votes for the non-moderate number is -1, then there must be a sum of votes for all numbers > 0.
Inference 2: If the sum of the votes of the first a numbers in the array = 0, then the sum of the votes of the remaining (n−a) numbers in the array must still be >0, that is, the mode of the last (n−a) numbers is still x.
insert image description here
According to the above inference, the first element of the record group is n 1 n_1n1mode is xxx , traverse and count the number of votes, when the sum of votes= 0 =0=When 0 , the mode of the remaining array must not change, this is because:

  • when n 1 = x n_1=xn1=x : half of all numbers canceled out are the modexxx
  • When n 1 ! = x n_1 != xn1!=x : Among all the numbers offset, the modexxThe number of x is at least 0 and at most half.

Using this feature, each round of assumptions that the sum of votes = 0 can reduce the remaining array interval. When the traversal is complete, the number assumed for the last round is the mode number.
Algorithm flow:
1. Initialization: votes = 0, mode x;
2. Loop: traverse each number num in the array nums;

		1.当 票数 votes 等于 0 ,则假设当前数字 num 是众数;
		2.当 num = x 时,票数 votes 自增 1 ;当 num != x 时,票数 votes 自减 1 ;

3. Return value : just return x;

class Solution{
    
    
public:
	int majorityElement(vector<int>& nums){
    
    
		int x = 0, votes = 0, count =0;
		for(int num : nums){
    
    
			if(votes == 0) x = num;
			votes += num  == x ? 1:-1;
		}
		//验证x是否为众数
		for(int num : nums){
    
    
			if(num == x) count ++;
			
		}
		return count > nums.size() / 2 ? x :0;//当无众数时返回0
	}
};

Reference: https://leetcode.cn/problems/shu-zu-zhong-chu-xian-ci-shu-chao-guo-yi-ban-de-shu-zi-lcof/solution/mian-shi-ti- 39-shu-zu-zhong-chu-xian-ci-shu-chao-3/

Guess you like

Origin blog.csdn.net/qq_43679351/article/details/124876535