Simple C++ Solution with HashTable


  • 0
    K

    Here is the code:

    int findShortestSubArray(vector<int>& nums) {
            //the hashtable recorded every position of x in nums, 
            //you can record only the start/end index instead.
            unordered_map<int, vector<int>> hash;
            int maxsize = 0;
            //create hash table
            for(int i = 0; i < nums.size(); i++){
                hash[nums[i]].push_back(i);
                //check the maximum frequency  
                if(hash[nums[i]].size()>maxsize) maxsize=hash[nums[i]].size();
            }
            //find the shortest subarray 
            int res = INT_MAX;
            for(auto x : hash){
                if(x.second.size() == maxsize){
                    res = min(res, (x.second[x.second.size() - 1] - x.second[0] + 1));
                }
            }	
            return res; 
        }
    

Log in to reply
 

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