LeetCode 697. 数组的度 Degree of an Array (Easy)

class Solution {
public:
    int findShortestSubArray(vector<int>& nums) {
          //构建哈希表并计算度
        unordered_map<int, int> hashMap;
        int degree = 0;
        for (int num : nums)
            degree = max(degree, ++hashMap[num]);

        int shortest = nums.size();
        for (auto num : hashMap)
        {   
            if (num.second == degree)
            {
                //左右逼近
                int start = 0, end = nums.size() - 1;
                while (nums[start] != num.first) 
                    ++start;
                while (nums[end] != num.first) 
                    --end;
                int cnt = end - start + 1;  //对应子数组长度
                shortest = min(shortest, cnt);
            }
        }
        return shortest;
    }
};

猜你喜欢

转载自www.cnblogs.com/ZSY-blog/p/12919167.html