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.
Ideas:
Finds a number in an array that has more than half occurrences. Sorting, hashing and other methods do not mention, considering the complexity of O (n), there is a legendary Moore voting algorithm available. In fact, it is also very simple, the initial selection of the first element, in turn compared to it and other elements, if equal to the number of votes plus one, or minus one, when its vote is 0 o'clock, replace the voting object is the current element, continue to execute, the result can be obtained (the existence of such a number in the array, otherwise, Depends on the order in which the elements are placed).
C++:
1 classSolution {2 Public:3 intMajorityelement (vector<int> &num) {4 5 intLen =num.size ();6 if(len = =0)7 return 0;8 9 intCNT =0, ret = num[0];Ten for(inti =0; i < Len; i++) One { A if(CNT = =0) - { -RET =Num[i]; thecnt++; - } - Else - { + if(Num[i] = =ret) -cnt++; + Else Acnt--; at } - } - returnret; - } -};
Python:
1 classSolution:2 #@param {integer[]} nums3 #@return {integer}4 defmajorityelement (Self, nums):5RET, CNT =0, 06 7 forValinchNums:8 ifCNT = =0:9RET =ValTenCNT = 1 One Else: A ifRET = =Val: -CNT = cnt + 1 - Else: theCNT = cnt-1 - returnret -
"Leetcode 169" Majority Element