C++ 16 lines O(n) Time O(n) Space


  • 0
    class Solution {
    public:
        int findShortestSubArray(vector<int>& nums) {
            unordered_map<int, int> cnt, begin;
            int freq = 0, res = INT_MAX;
            for (int i = 0; i < nums.size(); i++) {
                int n = nums[i];
                if (!begin.count(n)) begin[n] = i;
                if (++cnt[n] >= freq) {
                    res = cnt[n] == freq ? min(i - begin[n] + 1, res) : i - begin[n] + 1;
                    freq = cnt[n];
                }                
            }
            return nums.empty() ? 0 : res;
        }
    };
    

Log in to reply
 

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