Moderate

Given an  array of size n  , find the mode in it. The mode is the element that occurs more than once in the array  ⌊ n/2 ⌋ .

You can assume that the array is non-empty and that a given array always has a mode.

 

answer:

 1 class Solution {
 2 public:
 3     int majorityElement(vector<int>& nums) {
 4     if(nums.size()==1)
 5     {
 6         return nums[0];
 7     }
 8         int number = nums[0];
 9         int count = 0;
10         for(int i = 0;i<nums.size();i++){
11             if(nums[i]==number){
12                 count++;}
13             else if (count ==0){
14                 number = nums[i];
15             }else{
16                 count--;
17             }
18         
19         }
20          return number;
21     }
22 };

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325909213&siteId=291194637
Recommended