Test instructions: Finds elements in the array that have more than N/3 elements.
Idea: 1, the number of elements over n/3 up to two
2, the array of 3 consecutive data for a group, a total of N/3 group, then if there is a qualifying element, this element must appear in a group two times
3, knowing the above two conditions, with the so-called Moore voting method, a total of two rounds,
First round: Find the two most frequently occurring elements, each storing two elements N1 and N2, if the third element is the same as one, increase the count cn1 or CN2, otherwise, clear N1 and N2, starting with the next data to re-count.
According to the second article, a large number of elements must be found, of course, the search is not necessarily greater than N/3.
Second round: Verify whether the two elements meet the conditions, that is, whether the number of occurrences is greater than N/3;
1 classSolution {2 Public:3vector<int> Majorityelement (vector<int>&nums) {4vector<int>v;5 intSize =nums.size ();6 intn1=0, n2=0, cn1=0, cn2=0;7 for(intI=0; i<size;i++)8 {9 if(nums[i]==N1)Ten { Oneans++; A } - Else if(nums[i]==n2) - { thecn2++; - } - Else if(cn1==0) - { +N1 =Nums[i]; -Ans =1; + } A Else if(cn2==0) at { -N2 =Nums[i]; -CN2 =1; - } - Else - { incn1--; -cn2--; to } + } - if(cn2==0&&size>0)//used to solve the situation [0 0] then2=nums[0]-1; *cn1=0; $Cn2=0;Panax Notoginseng for(intI=0; i<size;i++) - { the if(nums[i]==N1) +ans++; A if(nums[i]==n2) thecn2++; + } - if(cn1>size/3) $ V.push_back (N1); $ if(cn2>size/3) - V.push_back (n2); - returnv; the } -};
Majority Element II