作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址:https://leetcode.com/problems/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: 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:

  1. nums.length will be between 1 and 50,000.
  2. nums[i] will be an integer between 0 and 49,999.

题目大意

数组的度是出现次数最多的数字的出现次数。求一个最短子数组的长度,其度等于数组的度。

解题方法

求出最短相同子数组度的长度

题目大意:

给定非空非负整数数组,数组的度是指元素的最大出现次数。

寻找最大连续区间,使得区间的度与原数组的度相同。

想法很粗暴,直接求出整个数组的degree,然后找出所有的度等于该degree的数,找出最小度的数。

import collections
class Solution(object):
def findShortestSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == len(set(nums)):
return 1
counter = collections.Counter(nums)
degree_num = counter.most_common(1)[0]
most_numbers = [num for num in counter if counter[num] == degree_num[1]]
scale = 100000000
for most_number in most_numbers:
appear = [i for i,num in enumerate(nums) if num == most_number]
appear_scale = max(appear) - min(appear) + 1
if appear_scale < scale:
scale = appear_scale
return scale

上面使用了Counter,下面的直接数,速度有一点提高。

import collections
class Solution(object):
def findShortestSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums_set = set(nums)
if len(nums) == len(nums_set):
return 1
degree = max([nums.count(num) for num in nums_set])
most_numbers = [num for num in nums_set if nums.count(num) == degree]
scale = 100000000
for most_number in most_numbers:
appear = [i for i,num in enumerate(nums) if num == most_number]
appear_scale = max(appear) - min(appear) + 1
if appear_scale < scale:
scale = appear_scale
return scale

上面的不够快是因为重复计算了多次的nums.count(num),避免重复计算可以使用字典进行保存。这个方法超出了96.7%的提交。

import collections
class Solution(object):
def findShortestSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums_set = set(nums)
if len(nums) == len(nums_set):
return 1
num_dict = {num:nums.count(num) for num in nums_set}
degree = max(num_dict.values())
most_numbers = [num for num in nums_set if num_dict[num] == degree]
scale = 100000000
for most_number in most_numbers:
appear = [i for i,num in enumerate(nums) if num == most_number]
appear_scale = max(appear) - min(appear) + 1
if appear_scale < scale:
scale = appear_scale
return scale

还能更快吗?可以。把能压缩的列表表达式拆开,这样迭代一次就可以了。最后用了个提前终止,如果scale==degree说明这段子列表里没有其他元素了,一定是最短的。

这个方法超过了99.91%的提交。

import collections
class Solution(object):
def findShortestSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums_set = set(nums)
if len(nums) == len(nums_set):
return 1
num_dict = {}
degree = -1
for num in nums_set:
_count = nums.count(num)
num_dict[num] = _count
if _count > degree:
degree = _count
most_numbers = [num for num in nums_set if num_dict[num] == degree]
scale = 100000000
for most_number in most_numbers:
_min = nums.index(most_number)
for i in xrange(len(nums)-1, -1, -1):
if nums[i] == most_number:
_max = i
break
appear_scale = _max - _min + 1
if appear_scale < scale:
scale = appear_scale
if scale == degree:
break
return scale

使用堆求最大次数和最小长度

二刷的时候,想到其实同时优化两个指标:最大次数和最小长度。所以,直接遍历所有的数字,同时统计它的次数,起始位置和结束位置,然后用一个堆,进行最大次数和最小长度的选择,对应的长度就是最小长度。

class Solution:
def findShortestSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
count = collections.defaultdict(tuple)
for i, num in enumerate(nums):
if num not in count:
count[num] = (1, i, i)
else:
count[num] = (count[num][0] + 1, count[num][1], i)
heap = [(-times, end - start + 1) for times, start, end in count.values()]
heapq.heapify(heap)
return heapq.heappop(heap)[1]

保存最左边出现位置和最右边出现位置

使用两个字典,保存每个数字出现的最左边和最右边位置,这样的话,我们找到了出现次数等于数组的度的数字,然后看它的长度是不是最小的即可。

class Solution:
def findShortestSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
left, right = dict(), dict()
count = collections.defaultdict(int)
for i, num in enumerate(nums):
if num not in left:
left[num] = i
right[num] = i
count[num] += 1
degree = max(count.values())
res = float("inf")
for num, c in count.items():
if c == degree:
res = min(res, right[num] - left[num] + 1)
return res

日期

2018 年 1 月 23 日
2018 年 11 月 16 日 —— 又到周五了!

【LeetCode】697. Degree of an Array 解题报告(Python)的更多相关文章

  1. 【LeetCode】697. Degree of an Array 解题报告

    [LeetCode]697. Degree of an Array 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/degree- ...

  2. LeetCode 697. Degree of an Array (数组的度)

    Given a non-empty array of non-negative integers nums, the degree of this array is defined as the ma ...

  3. LeetCode: Search in Rotated Sorted Array 解题报告

    Search in Rotated Sorted Array Suppose a sorted array is rotated at some pivot unknown to you before ...

  4. [LeetCode] 697. Degree of an Array 数组的度

    Given a non-empty array of non-negative integers nums, the degree of this array is defined as the ma ...

  5. leetcode 697. Degree of an Array

    题目: Given a non-empty array of non-negative integers nums, the degree of this array is defined as th ...

  6. 【LeetCode】26. Remove Duplicates from Sorted Array 解题报告(Python&C++&Java)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 双指针 日期 [LeetCode] https:// ...

  7. 【LeetCode】912. Sort an Array 解题报告(C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 库函数排序 桶排序 红黑树排序 归并排序 快速排序 ...

  8. 【LeetCode】941. Valid Mountain Array 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 题目地址:https://leetcode.c ...

  9. 【LeetCode】88. Merge Sorted Array 解题报告(Java & Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 新建数组 日期 题目地址:https://leetc ...

随机推荐

  1. 推荐一个latex简历模板的网站给大家

    http://www.rpi.edu/dept/arc/training/latex/resumes/ Using the LaTeX Resume Templates A group of resu ...

  2. CAN总线常见的两种编码格式(Intel/Motorola)

    在汽车电子行业的开发或者测试中,我们经常会看到CAN总线信号的常见的两种编码格式:Intel格式与Motorola格式. 讲解这两种格式之前,我们先来了解一些大端模式和小端模式,会对后面理解这两种编码 ...

  3. 使用Redis实现令牌桶算法

    在限流算法中有一种令牌桶算法,该算法可以应对短暂的突发流量,这对于现实环境中流量不怎么均匀的情况特别有用,不会频繁的触发限流,对调用方比较友好. 例如,当前限制10qps,大多数情况下不会超过此数量, ...

  4. API 管理在云原生场景下的机遇与挑战

    作者 | 张添翼 来源 | 尔达Erda公众号 ​ 云原生下的机遇和挑战 标准和生态的意义 自从 Kubernetes v1.0 于 2015 年 7 月 21 日发布,CNCF 组织随后建立以来,其 ...

  5. accommodate, accompany

    accommodate 词源: to make fit, suitable; 近/反义词: adapt, adjust, lodge; disoblige, incommode, misfit Lod ...

  6. const与指针的三种形式

    使用指针时涉及到两个对象:该指针本身和被它所指的对象. 将一个指针的声明用const"预先固定"将使那个对象而不是使这个指针成为常量.要将指针本身而不是被指对象声明为常量,必须使用 ...

  7. Linux系统根目录下各文件夹介绍

    参考自:[1]Linux 系统根目录下各个文件夹的作用 https://www.cnblogs.com/jiangfeilong/p/10538795.html[2]了解Linux根目录"/ ...

  8. JAVA平台AOP技术研究

    3.1 Java平台AOP技术概览 3.1.1 AOP技术在Java平台中的应用 AOP在实验室应用和商业应用上,Java平台始终走在前面.从最初也是目前最成熟的AOP工具--AspectJ,到目前已 ...

  9. 什么是微服务,SpringBoot和SpringCloud的关系和区别

    什么是微服务? 就目前而言对于微服务业界没有一个统一的,标准的定义.但通常而言,微服务是一种架构模式或者说是一种架构风格,它提倡单一应用程序划分为一组小的服务,每个服务在其独立的自己的进程中,服务之间 ...

  10. java关键字volatile内存语义详细分析

    volatile变量自身具有下列特性. 1.可见性.对一个volatile变量的读,总是能看到(任意线程)对这个volatile变量最后的写 入. · 2.原子性:对任意单个volatile变量的读/ ...