First, find the number of the congregation array ---

Given an array of size n, the number of them find the congregation. The mode refers to the number of occurrences in the array is greater than ⌊ n / 2 ⌋ elements.

You can assume that the array is non-empty, and there is always a given array number of the congregation.

Example 1:

Input: [3,2,3]
Output: 3
Example 2:

Input: [2,2,1,1,1,2,2]
Output: 2

Note: There is always the mode means that only a minority of the number of unique number, the number of the congregation at least one more than the second and more.

method 1:

First sort, that number is certainly in the middle of the mode

. 1  class Solution {
 2  public :
 . 3      static  BOOL CMP ( const  int & A, const  int & B) {
 . 4          return A < B;
 . 5      }
 . 6      int majorityElement (Vector < int > & the nums) {
 . 7          Sort (nums.begin ( ), nums.end (), cmp); // actually do not write cmp, the default ascending sort. Ascending: less <int> (); Descending: Greater <int> () 
. 8          return the nums [nums.size () / 2 ];
 . 9      }
 10 };

Method two: Moore referendum law

Stack container implementation:

 1 class Solution {
 2 public:
 3     int majorityElement(vector<int>& nums) {
 4     stack<int> my_stack;
 5     my_stack.push(nums[0]);
 6     for(int i=1;i<nums.size();i++){
 7         if(my_stack.empty() || my_stack.top() == nums[i]){
 8             my_stack.push(nums[i]);
 9         }
10         else{
11             my_stack.pop();
12         }
13     }
14     return my_stack.top();
15     }
16 };

Algorithm:

 1 class Solution {
 2 public:
 3     int majorityElement(vector<int>& nums) {
 4         int res=nums[0];
 5         int count=1;
 6         for(int i=1;i<nums.size();i++)
 7         {
 8             if(res==nums[i])
 9                 count++;
10             else
11             {
12                 count--;
13 is                  IF (COUNT == 0 )
 14                      RES the nums = [I + . 1 ]; // For all the numbers certainly exist, so the count = 0, must exist. 1 + I
 15              }
 16          }
 . 17          return RES;
 18 is      }
 . 19 };

 

Guess you like

Origin www.cnblogs.com/pacino12134/p/10994411.html