[Turn] mole Detailed voting algorithm

Disclaimer: This article is csdn bloggers original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https: //blog.csdn.net/u014248127/article/details/79230221


Moore algorithm can also be called the vote a majority voting algorithm, to see when I see leetcode 169 (Majority Element) title algorithms. This article explains Moore voting algorithm departure principles and advantages from leetcode 169 (Majority Element), while from leetcode 229 (Majority Element2) explain improve and extend Moore voting algorithm. (This article is all code python code)

A, Majority Element Title Description: Given an array of length n of the time, to identify the main elements thereof, i.e. the number of times the element occurs in the array is greater than the rounding n / 2 in. The title has been assumed to contain some element array, and the main elements must exist. What are some common methods:

1, each element traversing the dictionary and count (python):

dic = {}
for x in nums:
if x in dic:
dic[x] += 1
else:
dic[x] = 1
for key,value in dic.items():
if value > len(nums)/2:
return key

2, sort: sorted, there is certainly more than half the number of the intermediate (Python)

nums.sort()
return nums[len(nums)//2]

Second, Moore voting algorithm: time and space are very low mole voting algorithm, time complexity is O (n), space complexity is O (1), which is the reason for selecting covered algorithm.

1, the algorithm principle: each time to find a different pair from an array of elements, they are removed from the array down through the complete array. Since this question has already explained that there must be a number occurs more than half of the elements, so after traversing the complete array will be at least one element in the array.

Algorithm defined in the local variable a sequence element (m) and a counter (I), the case where the initialization counter is zero;
algorithm sequentially scan elements in a sequence, when the processing element x, if the counter is 0, then x assigned to m, then the counter (i) is set to 1;
if the counter is not 0, then m and comparing the sequence element x, if they are equal, then the counter is incremented by 1, if not equal, then the counter is decremented.
After processing, the last stored sequence elements (m), is the largest element in this sequence.
(Not sure if m storage elements is the largest element, can also be determined whether a second scan up element)
2, pseudocode (python):

Initialization element m = 0, = counter COUNT 0; 
Each number in the array to traverse X: 
IF I = 0: 
m = X and COUNT. 1 =
 the else  IF m = X: 
COUNT = COUNT +. 1
 the else : 
COUNT = COUNT -. 1 
Return m

3, Moore Majority Element voting algorithm (C ++):

class Solution {
public:
    bool check_Solution(vector<int> &numbers,int x){
        int cnt=0,len=numbers.size();
        for(int i=0;i<len;i++){
            if(numbers[i]==x)
                cnt++;
        }
        return (2*cnt>len)?true:false;
    }
    int MoreThanHalfNum_Solution(vector<int> numbers) {
        if(numbers.size()==0) return 0;
        int cnt=0,num;
        for(int i=0;i<numbers.size();i++){
            if(cnt==0){
                num=numbers[i];
                cnt==1;
            }
            if(num==numbers[i])
                cnt++;
            else
                cnt--;
        }
        if(check_Solution(numbers,num))
            return num;
        else
            return 0;
    }
};

 

Third, the improved algorithm Moore vote:

1, Title: LeetCode 229 [Majority Element II]
Given an array of integers, to find all the main elements, the number of which is strictly greater than one third of the number of occurrences of the array elements in the array.

Algorithm: Each delete three different numbers, the last remaining must be more than a third of the number of occurrences, this idea can be extended to a number of elements that appear more than 1 / k times what.

Because the elements that appear more than n / 3 at most only two, we can maintain a beginning two numbers (num1, num2) and two counters (counter1, counter2);
through the array, and the same elements in the array or when num1 num2, counter1 corresponding counter2 plus or 1;
if counter1 is 0 or counter2, will traverse the element assigned to num1 or nums2;
otherwise counter2 counter1 and decremented by 1.
2, C ++ code is:

 

3, python codes:

num1, count1 = None, 0 
num2, count2 = None, 0
 for the X- in nums: # algorithm core, identify the main elements of candidate values 
IF the X-== num1: 
count1 + = 1
 elif the X-== num2: 
count2 + 1 =
 elif count1 is == 0: 
num1, count1 is = X,. 1
 elif count2 == 0: 
num2, count2 = X,. 1
 the else : 
count1 is - =. 1 
count2 - =. 1 

count1 is, count2 = 0,0
 for X in the nums: #Determining a candidate value is the true statistical main elements 
IF X == num1: 
count1 is + =. 1
 IF X == num2: 
count2 + =. 1 
RES = []
 IF count1 is> len (the nums) //. 3 : 
res.append (num1) 
IF count2> len (nums) // 3 : 
res.append (num2) 
return RES

 

Guess you like

Origin www.cnblogs.com/joelwang/p/11606944.html