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).
思路:
- 题目要求既要频率最大, 又要距离最小.
- 很明显的一点, 至少要遍历nums数组一遍, 要做到O(n), 关键是在遍历过程中记录当前频率值和距离值(空间换时间). 从而通过比较找到频率和距离找到当前最小距离.
- 如果nums中元素第一次出现, 用pos数组记录该值的初始位置, 频率变为1; 如果是再次出现的值, 频率+1(若频率大于当前最大频率, 则当前距离为最短距离;若频率等于当前最大频率,则取当前距离和最短距离的最小值;若频率小于当前最大频率,则无需更新最短距离).
注意⚠️:
数组下标问题!