记录了初步解题思路 以及本地实现代码;并不一定为最优 也希望大家能一起探讨 一起进步
一一遍历统计
def averageValue(nums):
"""
:type nums: List[int]
:rtype: int
"""
s,count = 0,0
for num in nums:
if num%6==0:
s+=num
count+=1
return 0 if count==0 else s//count
BFS遍历每一个节点
每删除一个节点 可能多出左右两个林
记录父节点以及自身是左子树还是右子树
如果当前节点需要删除 将父节点对应子树指向None
判断当前节点左右子树是否删除 如果不删除则加入
class TreeNode(object):
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def delNodes(root, to_delete):
"""
:type root: TreeNode
:type to_delete: List[int]
:rtype: List[TreeNode]
"""
s = set(to_delete)
ans = []
if root.val not in s:
ans.append(root)
l = [(root,None,0)]
while l:
tmp = []
for node,pre,pos in l:
if node.val in s:
if pos==1:
pre.left = None
elif pos==2:
pre.right = None
if node.left and node.left.val not in s:
ans.append(node.left)
if node.right and node.right.val not in s:
ans.append(node.right)
if node.left:
tmp.append((node.left,node,1))
if node.right:
tmp.append((node.right,node,2))
l = tmp
return ans
中序遍历一一对应
所以arr中相邻的两个节点可能是同个父节点下的左右节点
合并相邻节点 增加两数乘积 保留其中较大值
直到只剩一个数
使用单调递减栈 如果arr[i]>=arr[i+1] arr[i+1]<=arr[i+2]
如果arr[i]<=arr[i+2] 那么优先合并i,i+1最优
如果arr[i]>arr[i+2] 那么优先合并i+1,i+2
def mctFromLeafValues(arr):
"""
:type arr: List[int]
:rtype: int
"""
st=[]
ans = 0
for x in arr:
while st and st[-1]<=x:
y = st.pop()
if not st or st[-1]>x:
ans +=x*y
else:
ans +=st[-1]*y
st.append(x)
while len(st)>1:
x = st.pop()
ans += st[-1]*x
return ans
将甜蜜度排序
二分查找甜蜜度为d能够划分多少类
def maximumTastiness(price, k):
"""
:type price: List[int]
:type k: int
:rtype: int
"""
price.sort()
def check(d):
cnt = 1
pre = price[0]
for p in price:
if p>= pre+d:
cnt+=1
pre = p
return cnt
l,r = 0,(price[-1]-price[0])//(k-1)+1
while l+1<r:
mid = (l+r)//2
if check(mid)>=k:
l = mid
else:
r = mid
return l
l[i]代表前i个字符串中有几个符合条件
def vowelStrings(words, queries):
"""
:type words: List[str]
:type queries: List[List[int]]
:rtype: List[int]
"""
y = ["a","e","i","o","u"]
n=len(words)
l=[0]*(n+1)
for i,w in enumerate(words):
l[i+1]=l[i]
if w[0] in y and w[-1] in y:
l[i+1]=l[i]+1
ans = []
for i,j in queries:
ans.append(l[j+1]-l[i])
return ans
找到重读的一段i~j 判断其中字符是否还存在字符串其他位置
如果有那么长度必定可以有j-i+1
隔一个继续判断k>j+1是否与i相同 如果相同可以连接两段
def maxRepOpt1(text):
"""
:type text: str
:rtype: int
"""
from collections import Counter
c = Counter(text)
ans = 0
for i in range(len(text)):
j=i
while j<len(text) and text[j]==text[i]:
j+=1
curc = j-i
if curc<c[text[i]] and (j<len(text) or i>0):
ans = max(curc+1,ans)
k = j+1
while k<len(text) and text[k]==text[i]:
k+=1
ans = max(ans,min(k-i,c[text[i]]))
i=j
return ans
排序 双指针计算平均值
def distinctAverages(nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.sort()
s=set()
n = len(nums)
for i in range(n//2):
num = (nums[i]+nums[n-1-i])*1.0/2
s.add(num)
return len(s)