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
思路:
1,排序,计算出各个数字出现的概率
2,根据概率求出其对应的最短子序列的长度
#pragma once
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class Solution {
public:
int findShortestSubArray(vector<int>& nums) {
//排序
vector<int> temp = nums;
sort(temp.begin(), temp.end());
vector<int> A; //存放数字
vector<int>B;//存放对应的数字出现的次数
int a = nums.size();
vector <int> times = { 0,0,a}; //0是概率,1是数字,2是最短的长度
//从有序数组中遍历一次,并计算出每个数出现的次数
for (int i = 0; i < temp.size(); i++)
{
if (i == 0)
{
A.push_back(temp[i]);
B.push_back(1);
}
else if (temp[i] != temp[i - 1])
{
A.push_back(temp[i]);
B.push_back(1);
}
else
{
B[B.size()-1]++;
}
}
//计算概率最大的且子序列最短的
for (int i = 0; i < B.size(); i++)
{
if (times[0] <= B[i])//如果概率大于等于之前的,则计算短子序列哪个更短
{
vector <int> t{0, 0, 0};
for (int j = 0; j < nums.size(),t[0]<B[i]; j++)
{
if (nums[j] == A[i]&&t[0]==0)
{
t[0]++;
t[1] = j;
t[2] = j;
}
else if (nums[j] == A[i])
{
t[0]++;
t[2] = j;
}
}
if (B[i]>times[0]||times[2] > (t[2]-t[1]+1))
{
times[0] = B[i];
times[1] = A[i];
times[2] = (t[2] - t[1] + 1);
}
}
}
return times[2];
}
};