C++ solution, unordered_map


  • 1
    S

    vector[0] is used to count the times of the value, vector[0] is the start position and vector[1] is the end position.

    class Solution {
    public:
        int findShortestSubArray(vector<int>& nums) {
            unordered_map<int, vector<int>> mMap;
            
            int maxTimes =  0;
            for(int i = 0;i<nums.size();++i) {
                if(mMap[nums[i]].empty()) {
                    mMap[nums[i]].push_back(1);
                    mMap[nums[i]].push_back(i);
                    mMap[nums[i]].push_back(i);
                }
                else {
                    mMap[nums[i]][0]++;
                    mMap[nums[i]][2] = i;
                }
                maxTimes = max(maxTimes,mMap[nums[i]][0]);
            }
            if(maxTimes == 1) return 1;
            auto retVal = INT_MAX;
            for(auto &val:mMap) {
                if((val.second)[0]==maxTimes) retVal = min(retVal,(val.second)[2]-(val.second)[1]+1);
            }
            if(retVal == INT_MAX) retVal = 1;
            return retVal;
        }
    };
    

Log in to reply
 

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