2018.03.22 leetcode 打卡
2018-03-22 22:13
225 查看
697. Degree of an Array
【Dictionary.setdefault( )】
参考文章:https://www.cnblogs.com/elleblog/p/7533413.html
功能:如果字典中不存在该键,则将键值添加进字典,将默认值赋给该键
用setdefault()统计第一次出现的位置,因为如果出现多次,位置不会被覆盖
用list 统计最后一次出现的位置,因为如果出现多次,list的值会一直被覆盖
import numpy as np
class Solution:
def findShortestSubArray(self, nums):
#collections.Counter() 统计字典中每个value出现的次数
count = collections.Counter(nums)
#
first ={}
last = {}
#统计value的首尾位置
for i,v in enumerate(nums):
# value 第一次出现的位置,用setdefault()函数,因为不会被覆盖
first.setdefault(v,i)
# value 最后一次出现的位置,用列表求
last[v] = i
#list的深度,value出现最多的次数
degree = max(count.values())
# last[v] - first[v] +1 --------value第一次出现和最后一次出现相隔的个数
return min(last[v] - first[v] +1 for v in count if count[v] == degree)
【Dictionary.setdefault( )】
参考文章:https://www.cnblogs.com/elleblog/p/7533413.html
功能:如果字典中不存在该键,则将键值添加进字典,将默认值赋给该键
用setdefault()统计第一次出现的位置,因为如果出现多次,位置不会被覆盖
用list 统计最后一次出现的位置,因为如果出现多次,list的值会一直被覆盖
import numpy as np
class Solution:
def findShortestSubArray(self, nums):
#collections.Counter() 统计字典中每个value出现的次数
count = collections.Counter(nums)
#
first ={}
last = {}
#统计value的首尾位置
for i,v in enumerate(nums):
# value 第一次出现的位置,用setdefault()函数,因为不会被覆盖
first.setdefault(v,i)
# value 最后一次出现的位置,用列表求
last[v] = i
#list的深度,value出现最多的次数
degree = max(count.values())
# last[v] - first[v] +1 --------value第一次出现和最后一次出现相隔的个数
return min(last[v] - first[v] +1 for v in count if count[v] == degree)
相关文章推荐
- 2018.03.22 leetcode 打卡
- 2018.03.22 leetcode 打卡
- 2018.03.22 leetcode 打卡
- 2018.03.22 leetcode 打卡
- 2018.03.22 leetcode 打卡
- 2018.03.22 leetcode 打卡
- 2018.03.22 leetcode 打卡
- 2018.03.22 leetcode 打卡
- 2018.03.22 leetcode 打卡
- 2018.03.22 leetcode 打卡
- 2018.03.22 leetcode 打卡
- 2018.03.22 leetcode 打卡
- 2018.03.22 leetcode 打卡
- leetcode 打卡 2018.03.06 #766 Toepliz Matrix
- 2018.03.07 leetcode 打卡 #169. Majority Element
- 2018.03.09 leetcode 打卡 #pivotIndex
- 2018.03.14 leetcode 打卡 # 118 pascal triangel
- 2018.03.15 leetcode 打卡 #268. Missing Number
- 2018.03.20. leetcode 打卡
- 2018.04.01 leetcode 打卡