Can someone please tell me where I'm going wrong with the following code ?


  • 0
    T
    class Solution {
    public:
        vector<int> majorityElement(vector<int>& nums) {
            int n = nums.size();
            vector<int> res;
            sort(nums.begin(),nums.end());
            int count=1;
            int i=0,j;
            while(i<nums.size()){
                j=i+1;
                while(nums[i]==nums[j]){
                    count++;
                    j++;
                }
                if(count > n/3){
                    res.push_back(nums[i]);
                    count=1;
                }
                i=j;
            }
            return res;
        }
    };

  • 0
    T

    Got the mistake. have to set count=1 outside the if condition.


Log in to reply
 

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