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.
class Solution(object): def findShortestSubArray(self, nums): """ :type nums: List[int] :rtype: int """ # use pos_map to record num's start pos and end pos in nums pos_map = {} for i,n in enumerate(nums): if n not in pos_map: pos_map[n] = [i, i] else: pos_map[n][1] = i # find max_freq number (maybe have many) cnt = collections.Counter(nums) max_freq = 0 max_freq_num = [] for k,v in cnt.iteritems(): if v > max_freq: max_freq = v max_freq_num = [k] elif v == max_freq: max_freq_num.append(k) # find min degree return min(pos_map[n][1]-pos_map[n][0]+1 for n in max_freq_num)
精简代码:
class Solution: def findShortestSubArray(self, nums): """ :type nums: List[int] :rtype: int """ pos_map = {} for i,n in enumerate(nums): if n not in pos_map: pos_map[n] = [i, i] else: pos_map[n][1] = i cnt = collections.Counter(nums) max_freq_num = max(cnt.values()) return min(pos_map[n][1]-pos_map[n][0]+1 for n in cnt if cnt[n] == max_freq_num)
更精简的:
class Solution: def findShortestSubArray(self, nums): """ :type nums: List[int] :rtype: int """ c = collections.Counter(nums) first, last = {}, {} for i, v in enumerate(nums): first.setdefault(v, i) last[v] = i degree = max(c.values()) return min(last[v] - first[v] + 1 for v in c if c[v] == degree)
注意:
Python 字典(Dictionary) setdefault()方法
描述
Python 字典 setdefault() 函数和get() 方法类似, 如果键不存在于字典中,将会添加键并将值设为默认值。
语法
setdefault()方法语法:
dict.setdefault(key, default=None)
参数
- key -- 查找的键值。
- default -- 键不存在时,设置的默认键值。
返回值
如果字典中包含有给定键,则返回该键对应的值,否则返回为该键设置的值。
实例
以下实例展示了 setdefault() 函数的使用方法:
实例(Python 2.0+)
#!/usr/bin/python # -*- coding: UTF-8 -*- dict = {'runoob': '菜鸟教程', 'google': 'Google 搜索'} print "Value : %s" % dict.setdefault('runoob', None) print "Value : %s" % dict.setdefault('Taobao', '淘宝')
以上实例输出结果为:
Value : 菜鸟教程
Value : 淘宝