定级Easy。
一开始想前缀和浪费了很多时间,过了会发现可以直接滑窗求和减一下就可以了。
class Solution:
def minimumRecolors(self, blocks: str, k: int) -> int:
n = len(blocks)
s = [(1 if x == 'B' else 0) for x in blocks ]
x = sum(s[:k])
ans = k-x
for r in range(k,n):
l = r - k
x -= s[l]
x += s[r]
ans = min(ans,k-x)
return ans
定级Medium。
推规律推错了,wa一次。
然后replace暴力过的。
class Solution:
def secondsToRemoveOccurrences(self, s: str) -> int:
n = len(s)
ans = 0
t = s.replace('01','10')
while s != t:
s = t
ans += 1
t = s.replace('01','10')
return ans
链接: 6158. 字母移位 II
IQPU模型,我用了树状数组。
class BinIndexTree:
def __init__(self, size):
self.size = size
self.bin_tree = [0 for _ in range(size+5)]
def add(self,i,v):
while i<=self.size :
self.bin_tree[i] += v
i += self.lowbit(i)
def update(self,i,v):
val = v - (self.sum(i)-self.sum(i-1))
self.add(i,val)
def sum(self,i):
s = 0
while i >= 1:
s += self.bin_tree[i]
i -= self.lowbit(i)
return s
def lowbit(self,x):
return x&-x
def _point_query(self,i):
return self.sum(i)
def _interval_add(self,l,r,v):
self.add(l,v)
self.add(r+1,-v)
class Solution:
def shiftingLetters(self, s: str, shifts: List[List[int]]) -> str:
bt = BinIndexTree(50000)
for a,b,c in shifts:
bt._interval_add(a+1,b+1,1 if c == 1 else -1)
abc = 'abcdefghijklmnopqrstuvwxyz'
cba = {v:i for i,v in enumerate(abc)}
n = len(s)
ans = []
for i,c in enumerate(s):
ans.append(abc[(cba[c]+bt._point_query(i+1))%26])
return ''.join(ans)
定级Hard。
同样用了树状数组
,但是用的PUIQ模型。
逆向构造
是比较简单的思路。有序集合
SortedList来储存所有位置的0,当添加数字后删除这个位置的0,查询时只需lgN。class BinIndexTree:
def __init__(self, size):
self.size = size
self.bin_tree = [0 for _ in range(size+5)]
def add(self,i,v):
while i<=self.size :
self.bin_tree[i] += v
i += self.lowbit(i)
def update(self,i,v):
val = v - (self.sum(i)-self.sum(i-1))
self.add(i,val)
def sum(self,i):
s = 0
while i >= 1:
s += self.bin_tree[i]
i -= self.lowbit(i)
return s
def lowbit(self,x):
return x&-x
class Solution:
def maximumSegmentSum(self, nums: List[int], removeQueries: List[int]) -> List[int]:
n = len(nums)
nums = [0]+nums+[0]
removeQueries = [0]+removeQueries+[0]
# a = [0]*(n+2)
bt = BinIndexTree(n+2)
from sortedcontainers import SortedList
s = SortedList(range(n+2))
ans = [0]
for i in range(n,1,-1):
# a[i] = removeQueries[i]
c = removeQueries[i]+1
bt.add(c,nums[c])
s.remove(c)
l = s.bisect_left(c)-1
r = l + 1
# print(s[l],s[r],bt.bin_tree)
ans.append(max(ans[-1],bt.sum(s[r]-1)-bt.sum(s[l])))
return ans[::-1]