链接: 6245. 找出中枢整数
按题意模拟即可。
class Solution:
def pivotInteger(self, n: int) -> int:
s = (1+n)*n//2
p = 0
for i in range(1,n+1):
p += i
if p == s - p + i:
return i
return -1
链接: 6246. 追加字符以获得子序列
按题意模拟即可。
class Solution:
def appendCharacters(self, s: str, t: str) -> int:
m,n = len(s),len(t)
j = 0
for i,c in enumerate(s):
if j<n and t[j] == c:
j += 1
if j == n:
return 0
# print(n,j)
return n - j
链接: 6247. 从链表中移除节点
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:
"""最后的结果,head一定是最大的,且后缀同样满足这个属性,因此可以递归
"""
if not head :return head
nxt = self.removeNodes(head.next)
if not nxt:return head
if nxt.val > head.val :return nxt
head.next = nxt
return head
转化为前缀和+哈希表
class Solution:
def countSubarrays(self, nums: List[int], k: int) -> int:
n = len(nums)
a = []
mx =10**6
for v in nums:
if v < k:
a.append(-1)
elif v>k:
a.append(1)
else:
a.append(mx)
s = 0
d = Counter()
d[0] = 1
ans = 0
for i,v in enumerate(a):
s += v
ans += d[s-mx]+d[s-mx-1]
d[s] += 1
return ans
左右前缀和
class Solution:
def countSubarrays(self, nums: List[int], k: int) -> int:
n = len(nums)
d = {(0,0,0):1}
p = nums.index(k)
ans = 1
l,r = Counter(),Counter()
s = 0
for j in range(p+1,n):
s += 1 if nums[j]>k else -1
r[s] += 1
ans += r[0]+r[1]
s = 0
for j in range(p-1,-1,-1):
s += 1 if nums[j]>k else -1
l[s] += 1
ans += l[0]+l[1]
ans += l[0]*r[0]
for i in range(1,n):
ans += l[i]*r[-i]+l[i]*r[-i+1]+r[i]*l[-i]+r[i]*l[-i+1]
return ans