lintcode1078. 数组的度

给定由非负整数组成的非空数组,数组的度定义为出现频率最高的元素。
找出最短的连续子数组,并使得它和原数组有相同的度。返回该连续子数组的长度。

样例
样例 1:

输入: [2, 2]
输出: 2
样例 2:

输入: [1, 2, 2, 3, 1]
输出: 2
解释: 
输入数组的度是212都出现了两次。
具有相同度的子串包括:
[1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2]
其中长度最短为2。所以返回2。
注意事项
nums.length的范围在150,000之间。
nums[i]是范围为049,999的整数。
class Solution {
public:
    /**
     * @param nums: a list of integers
     * @return: return a integer
     */
    int findShortestSubArray(vector<int> &nums) {
        // write your code here
        map<int,int>temp;
        for (int i = 0; i < nums.size(); i++) {
            /* code */
            temp[nums[i]]++;
        }
        int num;
        int cnt=0;
        for (auto i : temp) {
            /* code */
            if(i.second>=cnt){num=i.first;cnt=i.second;}
        }
        int mins=nums.size();
        int maxs=-1;
        for (int i = 0; i < nums.size(); i++) {
            /* code */
            if(nums[i]==num) 
            {
                mins=min(mins,i);
                maxs=max(maxs,i);
            }
        }
        return maxs-mins+1;
    }
};
发布了330 篇原创文章 · 获赞 13 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43981315/article/details/103944025