title :
Given an array of size n, find the majority element. The majority element is the element, the appears more than times ⌊ n/2 ⌋ .
Assume that the array was non-empty and the majority element always exist in the array.
code : OJ Test via runtime:197 ms
1 classSolution:2 #@param num, a list of integers3 #@return An integer4 defmajorityelement (self, num):5 ifLen (num) = = 1:6 returnNum[0]7 8candidate =09Count =0Ten forIinchrange (len (num)): One ifCount = =0: Acandidate =Num[i] -Count + = 1 - Else: the ifNum[i] = =Candidate: -Count + = 1 - Else: -Count-= 1 + returnCandidate
Ideas :
I can't think of this myself. Find the Moore voting algorithm on the Internet.
This method is still relatively unpretentious in thinking, but very subtle.
Pay attention to the condition of the topic, repeat the number of elements greater than half the length of the data.
Therefore, it is possible to adopt a hedging idea: once the next two elements are different, the two elements are hedged off; since the frequency of the majority is greater than the number of all other elements, the last of these hedging offsets must be the majority.
I've seen several journals before, and that's a good question. Record below:
Http://www.yanyulin.info/pages/2014/12/851338983752.html
http://www.geeksforgeeks.org/majority-element/
http://bookshadow.com/weblog/2014/12/22/leetcode-majority-element/
Leetcode "Majority Element" Python implementation