Advertisement
nikunjsoni

229

Jun 25th, 2021
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.99 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     vector<int> majorityElement(vector<int>& nums) {
  4.         int cand1, cand2, count1, count2;
  5.         cand1 = cand2 = INT_MAX; count1 = count2 = 0;
  6.        
  7.         for(int num: nums){
  8.             if(cand1 == num){
  9.                 count1++;
  10.             }
  11.             else if(cand2 == num){
  12.                 count2++;
  13.             }
  14.             else if(count1 == 0){
  15.                 count1++;
  16.                 cand1 = num;
  17.             }
  18.             else if(count2 == 0){
  19.                 count2++;
  20.                 cand2 = num;
  21.             }
  22.             else{
  23.                 count1--;
  24.                 count2--;
  25.             }
  26.         }
  27.        
  28.         count1 = count2 = 0;
  29.         for(int num: nums){
  30.             if(cand1 == num) count1++;
  31.             if(cand2 == num) count2++;
  32.         }
  33.         vector<int> ans;
  34.         if(count1 > nums.size()/3) ans.push_back(cand1);
  35.         if(count2 > nums.size()/3) ans.push_back(cand2);
  36.         return ans;
  37.     }
  38. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement