[leetcode] 697. Degree of an Array

网友投稿 759 2022-10-01

[leetcode] 697. Degree of an Array

[leetcode] 697. Degree of an Array

Description

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: 2Explanation: 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.

分析

题目的意思是:给你一个数组,给了一个degree的定义:这个数组中元素的频率。求出与原数组中degree相同的子数组的最短长度。

用hash表存放次数,用另一个hash表存放该数值在数组的起始位置和结束位置。最后把degree的最大的几个数取出来,取最小长度就行了。

代码

class Solution {public: int findShortestSubArray(vector& nums) { unordered_map m; unordered_map> pos; int degree=0; for(int i=0;i

参考文献

​​[LeetCode] Degree of an Array 数组的度​​

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:微信小程序看不了广告怎么办?(微信小程序看不了广告怎么办苹果)
下一篇:springboot集成本地缓存Caffeine的三种使用方式(小结)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~