Test instructions
Given an array of size n, find the majority element. The majority element is the element, which appears more than? N/2? Times.
Assume that the array was non-empty and the majority element always exist in the array.
Ideas:
Find the number of occurrences greater than N/2 in the array.
In C + +, map is particularly handy for this number of statistics, and Python is of course used in dictionaries.
Code:
C++
Class Solution{public: int majorityelement (vector<int> &num) { Vector<int>::iterator it = Num.begin (); int n = num.size (); map<int,int> count; for (; it! = Num.end (); it++) { //Why is there no need to determine the existence of a key here? Initialize to 0 if (++count[*it] > N/2) { return *it; }} } because it does not exist;
Python:
Class solution: # @param num, a list of integers # @return An integer def majorityelement (self, num): coun t = Dict ([]) flag = len (num)/2 for item in num: if item in count: count[item] = Count[item] + 1 else:< C9/>count[item] = 1 if Count[item] > flag: return item
"Leetcode" Majority Element