Given an integer array of size n, find all elements this appear more than times ? n/3 ?
. The algorithm should run in linear time and in O (1) space.
Hint:
- How many majority elements could it possibly?
- Do you have a better hint? Suggest it!
This question is about Moore's voting law. Specifically, you can refer to Grandyang's explanation. The code is as follows
Publicilist<int> Majorityelement (int[] nums) { intm =0; intn =0; intCM =0; intCN =0; foreach(varNuminchnums) { if(m = = num) cm++; Else if(n = = num) cn++; Else if(cm = =0) {cm=1; M=num; } Else if(cn==0) {cn=1; N=num; } Else{cm--; CN--; }} cm=0; CN=0; foreach(varNuminchnums) { if(m = = num) cm++; Else if(n = = num) cn++; } varres =Newlist<int>(); if(cm > Nums. Count ()/3) Res. ADD (m); if(CN > Nums. Count ()/3) Res. ADD (n); returnRes; }
Note several corner case
[0,0,0], this requires the second cycle of the time must be if else, if not, will return [0,0].
[0,1] It is also important to note that the last cm CN is to be greater than or greater than equals. Otherwise this output is going to work [0,1]
229. Majority Element II