码迷,mamicode.com
首页 > 编程语言 > 详细

Majority Element ,算法设计大作业1.py

时间:2017-10-08 14:43:24      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:more   var   算法设计   mes   enc   this   get   center   style   

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

标签:more   var   算法设计   mes   enc   this   get   center   style   

原文地址:http://www.cnblogs.com/Teddykin/p/7637319.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!