Leetcode刷题79-697. 数组的度(C++详细解法!!!)

Come from : [https://leetcode-cn.com/problems/degree-of-an-array/]

697. Degree of an Array

  • 1.Question
  • 2.Answer
  • 3.大神们的解决方案
  • 4.我的收获

1.Question

Given a non-empty array of non-negative integers nums, the degree of this array is defined as the maximum frequency of any one of its elements.

Your task is to find the smallest possible length of a (contiguous) subarray of nums, that has the same degree as nums.

Example 1 :

Input: [1, 2, 2, 3, 1]
Output: 2
Explanation: 
The input array has a degree of 2 because both elements 1 and 2 appear twice.
Of the subarrays that have the same degree:
[1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2]
The shortest length is 2. So return 2.

Example 2 :

Input: [1,2,2,3,1,4,2]
Output: 6

Note :

1. nums.length will be between 1 and 50,000.
2. nums[i] will be an integer between 0 and 49,999.

2.Answer

easy 类型题目。是我太菜么。。。这题不简单啊 啊 啊

class Solution {
public:
    int findShortestSubArray(vector<int>& nums) {
        int numsSize = nums.size(), res = INT_MAX, degree = 0;
        unordered_map<int, int> numsCnt;//记录各个数字出现的次数
        unordered_map<int, pair<int, int>> pos;//记录各个数字第一次、最后一次出现的下标
        for (int i = 0; i < numsSize; ++i) {
            if (++numsCnt[nums[i]] == 1) {
                //元素第一次出现
                pos[nums[i]] = {i, i};
            } 
            else {
                //更新最后出现的下标
                pos[nums[i]].second = i;
            }
            //更新出现次数最多的元素次数
            degree = max(degree, numsCnt[nums[i]]);
        }
        for (auto &item : numsCnt) {
            if (degree == item.second) {//此元素出现的次数等于数组的度
                //包含数组中出现的所有item.first需要的最少长度就是[pos[item.first].first, pos[item.first].second],第一次出现、最后一次出现
                res = min(res, pos[item.first].second - pos[item.first].first + 1);
            }
        }
        return res;
    }
};

3.大神们的解决方案

class Solution {
public:
    int findShortestSubArray(vector<int>& nums) {
        int *count= new int[50000];
        int *firstmeet= new int[50000];
        int dim=0;
        int ans=nums.size();
        for(int i=0;i<nums.size();i++)
        {
            int k=nums[i];
            if(count[k]==0)
            {
                firstmeet[k]=i;
            }
            count[k]++;
            if(count[k]>dim)
            {
                dim=count[k];
                ans=i-firstmeet[k]+1;
            }
            else if(count[k]==dim)
            {
                ans=min(ans,i-firstmeet[k]+1);
            }
        }
        return ans;
    }
};

4.我的收获

Fighting~~~
hash表啊 。。。
加强。。。

2019/5/15 胡云层 于南京 79

你可能感兴趣的:(LeetCode从零开始)