C++ Single pass very straightforward


  • 0
    X

    From the question, we know
    nums.length will be between 1 and 50,000.
    nums[i] will be an integer between 0 and 49,999.

    class Solution {
    public:
        int findShortestSubArray(vector<int>& nums) {
            int ret = 0, freq = 0;
            int m[50000] { }, n[50000] { };
            for (int i = 0; i < nums.size(); ++i) {
                if (!m[nums[i]]) n[nums[i]] = i;
                ++m[nums[i]];
                if (m[nums[i]] > freq) {
                    ret = i - n[nums[i]] + 1;
                    ++freq;
                } else if (m[nums[i]] == freq)
                    ret = min(ret, i - n[nums[i]] + 1);
            }
            return ret;
        }
    };
    

Log in to reply
 

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