1. 程式人生 > >Majority Element ,算法設計大作業1.py

Majority Element ,算法設計大作業1.py

you time some one size ssi none origin ans

Majority Element

Find majority element;

Input:An array A[1 to n] of elements;

Output:The majority element if it exists;otherwise none;

1Majority Element:

A majority element in an array A[] of size n is an element that appears more than n/2 times (and hence there is at most one such element).

The majority element is the element that occurs more than half of the size of the array. This means that the majority element occurs more than all other elements combined or if you count the number of times, majority element appears, and subtract the number of all other elements, you will get a positive number.

So if you count the number of some element, and subtract the number of all other elements and get the number 0 ,then your original element can‘t be a majority element.

2Algorithm:

Have two variables, counter and possible element. Iterate the stream, if the counter is 0 your overwrite the possible element and initialize the counter, if the number is the same as possible element - increase the counter, otherwise decrease it.

3、Pseudocode:

X<--candidate(1);

Count<--0;

For j<--1 to n;

if A[j]=x then count<--count + 1;

End for;

If count>[n/2] then return x;

Else return none;

Candidate(m):

j<--m,x<--A[m],count<--1;

While j<n and count>0:

j<--j+1;

If A[j]= x then count<--count+1;

else count <--count+1;

end while;

If j=n then return x;

else return candidate(j+1);

Source code:

#Python code

def majority_element(arr):

counter, possible_element = 0, None

for i in arr:

if counter == 0:

possible_element, counter = i, 1

elif i == possible_element:

counter += 1

else:

counter -= 1

return possible_element

技術分享

Eg: arr=[2,5,3,5,6,8,5,5]

Start:possible_element=None

Counter=0

When i=2 counter=1 possible_element=2

When i=5 counter=0 possible_element=2 # i!=possible_element , counter-1

When i=3 counter=1 possible_element=3

When i=5 counter=0 possible_element=3 # i!=possible_element , counter-1

When i=6 counter=1 possible_element=6

When i=8 counter=0 possible_element=6 # i!=possible_element , counter-1

When i=5 counter=1 possible_element=5

When i=5 counter=2 possible_element=5

return possible_element

Majority Element ,算法設計大作業1.py