Majority Element II

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.