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:

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.

原题地址: Degree of an Array

难度: Easy

题意: 先找出包含数量最多的值的子数组,返回最短的子数组长度.如上面例子,数量最多的数是1和2,包含1数字的子数组长度为5,包含2数字的子数组长度为2,所以返回2

思路:

(1)遍历数组,记录每个数值的数量已经最左边和最右边的索引值

(2)找出数量最多的数,返回长度

class Solution(object):
def findShortestSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
l, r = {}, {} # 记录数字最左边和最右边的索引
d = {} # 记录每个数字的数量
for i, num in enumerate(nums):
if num not in l:
l[num] = i
r[num] = i
d[num] = d.get(num, 0) + 1
degree = max(d.values()) # 找出值最大的数量
res = len(nums)
for i in d:
if d[i] == degree:
res = min(res, r[i] - l[i] + 1)
return res

时间复杂度: O(n)

空间复杂度: O(n)

最新文章

  1. JAVA装饰者模式(从现实生活角度理解代码原理)
  2. android之Handler机制
  3. JavaWeb---总结(十四)JSP原理
  4. 用javacsv API 来操作csv文件
  5. Delphi中TStringList类常用属性方法详解
  6. Cts框架解析(12)-ITargetPreparer
  7. bzoj 1187: [HNOI2007]神奇游乐园 插头dp
  8. python学习之字符串
  9. 理解和使用NT驱动程序的执行上下文
  10. javascript面向对象基础讲解(工厂模式、构造函数模式、原型模式、混合模式、动态原型模式)
  11. 2018-2019-1 20165231 实现mypwd(选做)
  12. liux三剑客grep 正则匹配
  13. 用反卷积(Deconvnet)可视化理解卷积神经网络还有使用tensorboard
  14. 修改git用户密码
  15. linux 命令杂集
  16. CSS 基础 例子 水平 & 垂直对齐
  17. LeetCode SQL:Employees Earning More Than Their Managers
  18. 直接IO 零拷贝 DAM 自缓存应用程序
  19. tomcat组成介绍和调优方案
  20. 19-2-28Python的了解以及变量、常量、数据类型、if语句的结构

热门文章

  1. [Xcode 实际操作]八、网络与多线程-(20)时间控件Timer定时功能
  2. IT兄弟连 JavaWeb教程 JSTL定义
  3. python 之 函数 装饰器
  4. (十四)SpringBoot开发微信授权支付
  5. ios wkwebview 跳转到新的controllerview加载页面 出现闪退问题
  6. Technocup 2017 - Elimination Round 1 (Unofficially Open for Everyone, Rated for Div. 2) B
  7. Hive_Hive的数据模型_内部表
  8. Jasper_table_resolve multiple copies of table in detail band issue
  9. Less学习(2)(完结)
  10. js 打开新窗口