1. 程式人生 > >Degree of an Array(697)

Degree of an Array(697)

697—Degree of an Array

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 1:

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.

C程式碼:

int findShortestSubArray(int* nums, int numsSize) {
    int pos[50001] = {0}; //initial position for every element in nums
    int freq[50001] = {0}; //frequency for every element in nums
int shortestDistance = numsSize; int currentDistance = 0; int maxFreq = 0; for(int i = 0;i < numsSize;i++) { if(pos[nums[i]] == 0) { //number turn out first time pos[nums[i]] = i + 1; // +1 to avoid situation: pos[nums[i]] = 0 freq[nums[i]]++; } else { freq[nums[i]]++; currentDistance = i - pos[nums[i]] + 2; if (freq[nums[i]] > maxFreq) { maxFreq =freq[nums[i]]; shortestDistance = currentDistance; } else if (freq[nums[i]] == maxFreq) { shortestDistance = currentDistance < shortestDistance ? currentDistance:shortestDistance; } } } if(maxFreq == 0) { //no element repeat! return 1; } return shortestDistance; }

Complexity Analysis:

Time complexity : O(n)
Space complexity : O(n).

思路:

  1. 題目要求既要頻率最大, 又要距離最小.
  2. 很明顯的一點, 至少要遍歷nums陣列一遍, 要做到O(n), 關鍵是在遍歷過程中記錄當前頻率值和距離值(空間換時間). 從而通過比較找到頻率和距離找到當前最小距離.
  3. 如果nums中元素第一次出現, 用pos陣列記錄該值的初始位置, 頻率變為1; 如果是再次出現的值, 頻率+1(若頻率大於當前最大頻率, 則當前距離為最短距離;若頻率等於當前最大頻率,則取當前距離和最短距離的最小值;若頻率小於當前最大頻率,則無需更新最短距離).

注意⚠️:

陣列下標問題!