1. 程式人生 > >[LeetCode] Degree of an Array

[LeetCode] Degree of an Array

重復 his out pub this lock put second 可能

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:

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

題目要求給定一個非空非負的整數數組,先求出數組的度,也就是出現次數最多的那個數字的出現次數。

然後找出這個數組的最小連續子數組並返回子數組的長度,要求這個子數組的度和原數組的度相同。

這是個很容易的題。就寫了一個思路簡單但是不夠簡潔的方法。

思路:首先利用map(m)求出給定數組的度,這裏需要註意的是有可能含有相同度的多個數字。所以用一個數組vec來存儲數組的度相同的數字。然後利用另一個map(n)來存儲數組中從尾到頭不同數字的索引(遍歷數組,用 map映射數值到索引,重復的數字就會被覆蓋並更新索引),這個索引也就是子數組的右邊界。最後利用兩層for循環,找出子數組的左邊界。並返回最小的子數組長度即可。

想法比較片段化,後續想出更簡單的方法再更新。

class Solution {
public:
    int findShortestSubArray(vector<int>& nums) {
        int degree = 0, val = 0, res = INT_MAX;
        unordered_map<int, int> m;
        for (int num : nums) 
            m[num]++;
        for (auto it = m.begin(); it != m.end(); it++) {
            
if (it->second > degree) { degree = it->second; } } vector<int> vec; for (auto it = m.begin(); it != m.end(); it++) { if (it->second == degree) { vec.push_back(it->first); } } unordered_map<int, int> n; for (int i = 0; i != nums.size(); i++) n[nums[i]] = i; for (int i = 0; i != vec.size(); i++) { int left = 0, right = n[vec[i]]; bool first = true; for (int j = 0; j != nums.size(); j++) { if (vec[i] == nums[j] && first) { left = j; first = false; } res = min(res, right - left + 1); } } return res; } }; // 279 ms

[LeetCode] Degree of an Array