697. Degree of an Array*
原创
©著作权归作者所有:来自51CTO博客作者珍妮的选择的原创作品,请联系作者获取转载授权,否则将追究法律责任
697. Degree of an Array*
https://leetcode.com/problems/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 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.
C++ 实现 1
来自 [Java/C++/Python] One Pass Solution
, 思路是:
在遍历 A
的过程中, 统计每个元素出现的次数, 以及首次出现的 index
, 之后不断更新 degree
以及 subarray 的 size. 用了两个哈希表.
class Solution {
public:
int findShortestSubArray(vector<int>& A) {
unordered_map<int, int> count, first;
int res = 0, degree = 0;
for (int i = 0; i < A.size(); ++i) {
if (first.count(A[i]) == 0) first[A[i]] = i;
if (++count[A[i]] > degree) {
degree = count[A[i]];
res = i - first[A[i]] + 1;
} else if (count[A[i]] == degree)
res = min(res, i - first[A[i]] + 1);
}
return res;
}
};
C++ 实现 2
我的非常暴力的解法, 速度非常慢. 思路:
- 统计最大的 degree, 将拥有最大 degree 的元素保存到
arr
中 - 使用双指针找到最小的 subarray 的大小.
class Solution {
public:
int findShortestSubArray(vector<int>& nums) {
unordered_map<int, int> records;
unordered_set<int> arr;
for (auto &a : nums) records[a] ++;
int degree = 0;
for (auto &p : records) degree = std::max(degree, p.second);
for (auto &p : records) {
if (p.second == degree) arr.insert(p.first);
}
int res = INT32_MAX;
for (auto &p : arr) {
int i = 0, j = nums.size() - 1;
while (i <= j) {
while (i <= j && nums[i] != p) ++ i;
while (i <= j && nums[j] != p) -- j;
res = std::min(res, j - i + 1);
break;
}
}
return res;
}
};
C++ 实现 3
来自 LeetCode Submission. 和 C++ 实现 1
思路一样, 不过哈希表定义为:
unordered_map<int, pair<int, int>>
代码如下:
class Solution {
public:
int findShortestSubArray(vector<int>& nums) {
int ret = INT_MAX, cur_max = 0;
unordered_map<int, pair<int, int>> m;
for(int i = 0; i < nums.size(); i++){
if(m.find(nums[i]) == m.end()){
m[nums[i]] = make_pair(0, i);
}
m[nums[i]].first++;
int degree = m[nums[i]].first, dist = i - m[nums[i]].second + 1;
if(cur_max < degree){
cur_max = degree;
ret = dist;
}
else if(cur_max == degree){
ret = min(ret, dist);
}
}
return ret;
}
};