排序
,倒序每取两个就跳过一个
class Solution:
def minimumCost(self, cost: List[int]) -> int:
cost.sort()
res = 0
i = len(cost) - 1
while i >= 0:
res += cost[i]
i -= 1
if i >= 0:
res += cost[i]
i -= 1
i -= 1
return res
前缀和
,找到最大最小值,并判断在low到up区间上,加上最大最小值是否在还符合在low到up区间
class Solution:
def numberOfArrays(self, differences: List[int], lower: int, upper: int) -> int:
for i in range(1, len(differences)):
differences[i] = differences[i] + differences[i - 1]
max_num = -10000001
min_num = 10000001
for difference in differences:
max_num = max(max_num, difference)
min_num = min(min_num, difference)
res = 0
for i in range(lower, upper + 1):
if i + min_num >= lower and i + max_num <= upper:
res += 1
return res
BFS
加自定义排序
class Solution:
def highestRankedKItems(self, grid: List[List[int]], pricing: List[int], start: List[int], k: int) -> List[
List[int]]:
queue = [start]
res = []
m, n = len(grid), len(grid[0])
used = set()
used.add((start[0], start[1]))
while queue:
next = []
cur = []
for node in queue:
row = node[0]
col = node[1]
for xi, yi in ((1, 0), (0, 1), (-1, 0), (0, -1)):
if 0 <= row + xi < m and 0 <= col + yi < n:
if grid[row + xi][col + yi] != 0 and (row + xi, col + yi) not in used:
used.add((row + xi, col + yi))
next.append([row + xi, col + yi])
if pricing[0] <= grid[row][col] <= pricing[1]:
cur.append([grid[row][col], row, col])
cur.sort(key=lambda x: (x[0], x[1], x[2]))
while cur and k:
node = cur.pop(0)
res.append([node[1], node[2]])
k -= 1
if k == 0:
return res
queue = next
return res
模拟
,只需考虑"S"的位置,并计算一组的后一个S位置到后一组的前一个S位置的距离,距离结果相乘。
class Solution:
def numberOfWays(self, corridor: str) -> int:
seat_index = []
for index in range(len(corridor)):
if corridor[index] == 'S':
seat_index.append(index)
if len(seat_index) % 2 != 0 or len(seat_index) == 0:
return 0
res, MOD = 1, 10 ** 9 + 7
for i in range(2, len(seat_index), 2):
res *= (seat_index[i] - seat_index[i - 1])
res %= MOD
return res