C++ solution using map (Fully explained in comments)


  • 0
    T
    int findShortestSubArray(vector<int>& nums) {
            map <int,int> r,l,cnt;//three maps for left index, right index and count
            for(int i=0;i<nums.size();++i) {
                int x=nums[i];
                if(!l[x]) l[x]=i+1;//i+1 for the case where max frequency element resides in index 0.
                r[x]=i+1,cnt[x]++;
            }
            int m=INT_MIN,size=INT_MAX;
            map<int,int> :: iterator it;
            
            for(it=cnt.begin();it!=cnt.end();++it) 
                m=max(m,it->second);//getting degree of the array
            
            for(it=cnt.begin();it!=cnt.end();++it) {
                if(it->second == m) {//the maximum occurring element
                    size=min(size,r[it->first]-l[it->first]+1);//get the size of the subarray and keep track of the minimum
                }
            }
            return size;
        }
    

Log in to reply
 

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