The main element of a data series is the element in the sequence that occurs more than half the length of the sequence.
Method 1 (Expected time complexity is O (n)):
Because the main element occurs more than half the length of the sequence, the main element must be the median. Recursive partitioning can be used to find the median, and the expected time complexity is O (n).
Act 2:
Obviously, if a sequence has the main element, then we remove the different two numbers in the sequence, and the main element of the remaining sequence is the same as the primary element of the original sequence.
Specific algorithm operation: Record two quantities, current element x, Count cnt. Initialize CNT to 0, then traverse the sequence, if CNT is 0, the x is set to the current element and the CNT to 1, otherwise, if the current element and X are the same, then cnt++, if the current element and X are different, then cnt--; after the traversal, X is the primary element.
The code is implemented as follows:
1 classSolution {2 Public:3 /**4 * @param nums:a list of integers5 * @return: The majority number6 */7 intMajoritynumber (vector<int>v) {8 //Write your code here9 intX, cnt =0;Ten for(intI=0; I!=v.size (); ++i) One { A if(cnt==0) x = V[i], cnt =1; - Elsev[i]==x?++cnt:--CNT; - } the returnx; - } -};
[Lintcode] Majority number (main element in time complexity O (n))