"Leetcode hash Table" Majority Element
@author: Wepon
@blog: http://blog.csdn.net/u012162613
1. Topics
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.
2. AnalysisTest instructions: Given an array of length n, find the majority element, the so-called majority element is the number of occurrences greater than N/2. very simple topic, many solutions:
- Runtime:o (n2)-brute Force solution: Check Each element if it is the majority element.
- Runtime:o (n), Space:o (n)-hash table: Maintain a Hash table of the counts of each element, T Hen find the most common one.
- Runtime:o (n log n)-sorting: Find the longest contiguous identical element in the array after sorting.
- Average Runtime:o (n), worst case runtime:infinity-randomization: Randomly pick an element and check If it is the majority element. If It isn't, do the random pick again until you find the majority element. As the probability to pick the majority element was greater than, the expected number of attempts is < 2.
- runtime:o (n log n )-divide and conquer : Divide the array into the other halves, then find the majority element A in the first half And the majority element B in the second half. The global majority element must either be A or B. If A = = B, then it automatically becomes the global majority element. If not, then both A and B were the candidates for the majority element, and it was suffice to check the count of occurrences For at the most of the candidates. The runtime complexity, T (n ) = t (n /2) + 2n = O ( n log n ).
- runtime:o (n )-moore voting algorithm : We Maintain a candidate and a counter initialized to 0. As we iterate the array, we look at the current element x:
- if the counter is 0, we set the current candidate to X and the counter to 1.
- if the counter is not 0, we increment or decrement the counter based on whether X are the current candidate.
After one pass, the current candidate is the majority element. Runtime complexity = O (n ).
- Runtime:o (n)-bit manipulation: We would need from iterations, each calculating the number of 1 's for the i< c2>th bit of all n numbers. Since A majority must exist, therefore, either count of 1 ' s > Count of 0 ' s or vice versa (but can never is equal). The majority number ' s ith bit must is the one bit that has the greater count.
The code for the hash table is given below, and the rest is written in the comments. 3. Code
int majorityelement (vector<int> &num) { unordered_map<int,int> map; int len=num.size (); for (int i=0;i<len;i++) { if (Map.find (Num[i]) ==map.end ()) map[num[i]]=0; else map[num[i]]++; if (MAP[NUM[I]]>=LEN/2) return num[i]; } }
"Leetcode hash Table" Majority Element