C++ Solution using 2 Unordered Maps


  • 0
    S
    class Solution {
    public:
        int findShortestSubArray(vector<int>& nums) {
            unordered_map<int, int>map;
            unordered_map<int, vector<int>>map1;
            int n = nums.size();
            int deg = INT_MIN, lastpos = INT_MAX;
            
            if(n<=1)
                return n;
            
            for(auto i : nums)
            {
                map[i]++;
                if(map[i] > deg)
                    deg = map[i];
            }
            for(int i=0;i<n;i++)
            {
                if(map[nums[i]] == deg)
                {
                    if(map1.find(nums[i]) == map1.end() || map1[nums[i]].size() == 1)
                        map1[nums[i]].push_back(i);
                    else
                    {
                        map1[nums[i]].pop_back();
                        map1[nums[i]].push_back(i);
                    } 
                }
            }
            for(auto i : map1){
              int diff;
                if(deg > 1)
                    diff = i.second[1] - i.second[0]+1;
                else
                    diff = i.second[0]+1;
                lastpos = min(lastpos, diff);
            }
            return lastpos;
        }
    };
    

Log in to reply
 

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