My c++ adhoc solution


  • 0
    A
    class Solution {
    public:
        int majorityElement(vector<int>& nums) {
              int i , len, max=0, count=1;
              len = nums.size();
              max = len/2;
              if(len%2)                     //for odd length//
              max=max+1;
              if(len==1)
              return nums[0];
              sort(nums.begin(),nums.end());
              for(i=0;i<len;i++)
                 {  if(nums[i]==nums[i+1])
                      count++;
                    else
                       {
                           if(count>=max)
                            return nums[i];
                           count=1;
                        }
                                  
                 }
             return 0;
            
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.