611. Valid Triangle Number: 还算是简单,不过好想对python的控制比较严格。其实只是固定最后一个值,然后找前两个值,找前两个值的时候直接利用对向型指针就可以了。
616. Add Bold Tag in String: 其实就是构造出一个字符串等长的True/False list,然后根据连续的True 或者 False 来构建就好了。
621. Task Scheduler: 这道题比较难,基本的想法就是先把高频的等间隔放好,然后依次填充低频的,但是写起来很tricky,有个很有趣的写法,就是在loop整个元素的时候,先把所有的pop一遍,然后加入到一个templist里,然后再从templist中选取和法的加回到heap里去,这样可以保证heap里的每一个元素都被访问一遍。
class Solution(object):
def leastInterval(self, tasks, n):
"""
:type tasks: List[str]
:type n: int
:rtype: int
"""
h = {}
for t in tasks:
h[t] = h.get(t, 0) + 1
heap = []
for key in h:
heapq.heappush(heap, [-h[key], key])
# 先按照频率由大到小放入heap
res = []
count = 0
res = []
while heap:
k = n + 1
tempList = []
while k > 0 and heap:
freq, val = heapq.heappop(heap) # most frequency task
freq = -freq
freq -= 1 # decrease frequency, meaning it got executed
tempList.append([-freq, val]) # collect task to add back to queue
k -= 1
count += 1 #successfully executed task
res.append(val)
for e in tempList:
if e[0] < 0:
heapq.heappush(heap, e) # add valid tasks
if not heap:
break
if k > 0:
res += ["idle"]*k
count = count + k # if k > 0, then it means we need to be idle
print res
return count
623. Add One Row to Tree: 这题比较简单一些,就是找出parent层,然后依次创建就可以了。
625. Minimum Factorization: greedy的想法是先找大的单位数factor,比如说9,8这类的,先找8,找不到在找4,因为8会合并位数。从大到小找到所有的单位数factor后,再合并一下。这题用backtracking也可以做,想法很类似
class Solution(object):
def smallestFactorization(self, a):
"""
:type a: int
:rtype: int
"""
if a == 1:
return 1
res = []
i = 1
while a > 1:
for i in range(9,1,-1):
if not a%i:
a = a//i
res += [i]
break
else:
return 0
ret = int(''.join(map(str,res[::-1])))
return ret if ret < 2 ** 31 else 0
634. Find the Derangement of An Array: 这题更多的是数学公式的推导:d(n)=(n−1)∗[d(n−1)+d(n−2)]得找到这个排列组合的公式。剩下来的用一下dp或者递归就可以了。
class Solution(object):
def findDerangement(self, n):
"""
:type n: int
:rtype: int
"""
MOD = 10**9 + 7
X, Y = 1, 0
for n in xrange(2, n+1):
X, Y = Y, (n - 1) * (X + Y) % MOD
return Y
635. Design Log Storage System: 开始做到竞赛的题目了,这题比较简单
636. Exclusive Time of Functions: 利用stack,看了答案,感觉这题应该是能写出来的,万万没想到,算是stack的比较直接的应用
class Solution(object):
def exclusiveTime(self, n, logs):
"""
:type n: int
:type logs: List[str]
:rtype: List[int]
"""
res = [0 for _ in range(n)]
stack = []
prev_id, prev_sign, prev_ts = logs[0].split(":")
stack.append(int(prev_id))
i = 1
prev_ts = int(prev_ts)
while i < len(logs):
s = logs[i].split(":")
if s[1] == "start":
if stack:
# stack store the previous visited process id
res[stack[-1]] += int(s[2]) - prev_ts
stack.append(int(s[0]))
prev_ts = int(s[2])
else:
res[stack[-1]] += int(s[2]) - prev_ts + 1
stack.pop()
prev_ts = int(s[2]) + 1
i += 1
return res
638. Shopping Offers: 看着像是个DP问题,其实是dfs,或者改进一些是记忆化搜索问题。
640. Solve the Equation: 勉强算是做出来了吧,但是写的code很长。