2021-12-12 每日打卡:Leetcode周赛 第271场
作者:互联网
一些废话
今天第一次做了leetcode周赛题目,ac了2道,总体感觉不错,下次还来。
限时编程能力不太够,第一题那么简单用了11分钟,因为我在读题……后面三道学聪明了,直接去看测试用例的解释,然后粗略的扫一遍题目关注细节。
还有wa的情况,千万要保留一下测试用例,否则还得再提交一遍wa。
环和杆
- 如果使用字典,要使用有默认值的字典!否则还要多花时间进行判断是否存在:
class Solution:
def countPoints(self, rings: str) -> int:
colors = collections.defaultdict(set)
for i in range(len(rings)//2):
colors[rings[i*2+1]].add(rings[i*2])
ans=0
for k in colors:
if len(colors[k])==3:
ans+=1
return ans
- 映射运算,
'B': 1, 'G': 2, 'R': 4
,这样就可以一直加加加啦
子数组范围和
- 错失,只能说相信自己好吧,认准了思路就做就是了
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
- 单调栈的做法【第一遍未做出】:
class Solution:
def subArrayRanges(self, nums: List[int]) -> int:
minSum = self.minSum(nums[::])
maxSum = self.maxSum(nums[::])
return maxSum - minSum
def minSum(self, arr):
arr.append(-0x7FFFFFFF)
stack = [-1]
res = 0
for i in range(len(arr)):
while stack and arr[stack[-1]] > arr[i]:
j = stack.pop()
k = stack[-1]
res += arr[j] * (i - j) * (j - k)
stack.append(i)
return res
def maxSum(self, arr):
arr.append(0x7FFFFFFF)
stack = [-1]
res = 0
for i in range(len(arr)):
while stack and arr[stack[-1]] < arr[i]:
j = stack.pop()
k = stack[-1]
res += arr[j] * (i - j) * (j - k)
stack.append(i)
return res
给植物浇水 II
- 比较简单,理解好题意即可
class Solution:
def minimumRefill(self, plants: List[int], capacityA: int, capacityB: int) -> int:
l, r, res = 0, len(plants)-1, 0
A, B = capacityA, capacityB
while l < r:
if A >= plants[l]:
A -= plants[l]
l += 1
else:
A = capacityA
res += 1
A -= plants[l]
l += 1
if B >= plants[r]:
B -= plants[r]
r -= 1
else:
B = capacityB
res += 1
B -= plants[r]
r -= 1
if l == r:
more = A if A > B else B
if more < plants[l]:
res += 1
return res
摘水果
- 这个题的关键是去思考发现:只有两种选择,折返一次or不折返,所以分为向左和向右走【第一遍未做出】
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
标签:plants,周赛,arr,12,int,res,self,打卡,stack 来源: https://blog.csdn.net/Can__er/article/details/121885509