5952. 环和杆
我的代码:执行用时: 20 ms 内存消耗: 15.1 MB
class Solution:
def countPoints(self, rings: str) -> int:
res = 0
arr = [set() for i in range(10)]
for i in range(0, len(rings), 2):
arr[int(rings[i+1])].add(rings[i])
for i in range(10):
if len(arr[i]) == 3:
res += 1
return res
5953. 子数组范围和
我的代码:执行用时: 3084 ms 内存消耗: 30.2 MB
class Solution:
def subArrayRanges(self, nums: List[int]) -> int:
lenn = len(nums)
res = 0
dp = [[0] * lenn for i in range(lenn)]
dp1 = [[0] * lenn for i in range(lenn)]
for i in range(lenn):
dp[i][i] = nums[i]
dp1[i][i] = nums[i]
for i in range(lenn):
for j in range(i+1, lenn):
n = nums[j]
a, b = dp[i][j-1], dp1[i][j-1]
if n < a:
dp[i][j] = n
dp1[i][j] = b
res += b - n
elif n > b:
dp[i][j] = a
dp1[i][j] = n
res += n - a
else:
res += b - a
dp[i][j] = a
dp1[i][j] = b
return res
大佬的代码:执行用时: 3028 ms 内存消耗: 15 MB
class Solution:
def subArrayRanges(self, nums: List[int]) -> int:
n = len(nums)
ans = 0
for i in range(n):
m = nums[i]
M = nums[i]
for j in range(i, n):
m = min(m, nums[j])
M = max(M, nums[j])
ans += M - m
return ans
5954. 给植物浇水 II
我的代码:执行用时: 136 ms 内存消耗: 25.6 MB
class Solution:
def minimumRefill(self, plants: List[int], capacityA: int, capacityB: int) -> int:
res = 0
lenp = len(plants)
index1, index2 = 0, lenp - 1
cpA, cpB = capacityA, capacityB
while index1 < index2:
if cpA < plants[index1]:
cpA = capacityA
res += 1
cpA -= plants[index1]
index1 += 1
if cpB < plants[index2]:
cpB = capacityB
res += 1
cpB -= plants[index2]
index2 -= 1
if index1 == index2:
aa = plants[index1]
if cpA < aa and cpB < aa:
res += 1
elif cpA< cpB and cpB < aa:
res += 1
return res
大佬的代码:执行用时: 108 ms 内存消耗: 25.8 MB
class Solution:
def minimumRefill(self, plants: List[int], capacityA: int, capacityB: int) -> int:
ret = 0
i, j = 0, len(plants)-1
curr_a, curr_b = capacityA, capacityB
while i < j:
if plants[i] > curr_a: # refill A
curr_a = capacityA
ret += 1
if plants[j] > curr_b: # refill B
curr_b = capacityB
ret += 1
curr_a -= plants[i] # A 浇水
curr_b -= plants[j] # B 浇水
i += 1
j -= 1
if i > j: # len(plants) = 偶数
return ret
else: # 奇数
return ret if max(curr_a,curr_b) >= plants[i] else ret+1
5955. 摘水果
大佬的代码:执行用时: 248 ms 内存消耗: 44.8 MB 双100%
class Solution:
def maxTotalFruits(self, fruits: List[List[int]], startPos: int, k: int) -> int:
h = deque([])
res = 0
n = len(fruits)
p = 0
#先从左边开始,找到能够到达的最远点,并把从最远的开始到startPos的所有水果加起来,同时入队
while p < n and fruits[p][0] <= startPos:
if abs(fruits[p][0] - startPos) <= k:
res += fruits[p][1]
h.append((fruits[p][0], fruits[p][1]))
p += 1
tmp = res
while p < n and fruits[p][0] - startPos <= k:
#对于每一个startPos右端的水果,依次检查左端点是否满足条件
while h and h[0][0] < startPos and fruits[p][0] - h[0][0] + min(startPos - h[0][0], fruits[p][0] - startPos) > k:
tmp -= h[0][1]
h.popleft()
tmp += fruits[p][1]
res = max(res, tmp)
p += 1
return res