Цена за 48 часов в ленте | 3800,00 |
Цена за 1 час закрепления | N/A |
Взаимопиар | Нет |
Дополнительные условия рекламы | Отсутствуют |
Input: root = [3,9,20,null,null,15,7]
Output: [3.00000,14.50000,11.00000]
from collections import deque
def averageOfLevels(root):
result = []
queue = deque([root])
while queue:
level_sum, level_count = 0, len(queue)
for _ in range(level_count):
node = queue.popleft()
level_sum += node.val
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
result.append(level_sum / level_count)
return result
Input: n = 2, logs = ["0:start:0","1:start:2","1:end:5","0:end:6"]
Output: [3,4]
def exclusiveTime(n, logs):
stack = []
times = [0] * n
prev_time = 0
for log in logs:
fid, typ, time = log.split(':')
fid, time = int(fid), int(time)
if typ == 'start':
if stack:
times[stack[-1]] += time - prev_time
stack.append(fid)
prev_time = time
else:
times[stack.pop()] += time - prev_time + 1
prev_time = time + 1
return times
Input
["LogSystem", "put", "put", "put", "retrieve", "retrieve"]
[[], [1, "2017:01:01:23:59:59"], [2, "2017:01:01:22:59:59"], [3, "2016:01:01:00:00:00"], ["2016:01:01:01:01:01", "2017:01:01:23:00:00", "Year"], ["2016:01:01:01:01:01", "2017:01:01:23:00:00", "Hour"]]
Output
[null, null, null, null, [3, 2, 1], [2, 1]]
class LogSystem:
def __init__(self):
self.logs = []
def put(self, id: int, timestamp: str) -> None:
self.logs.append((id, timestamp))
def retrieve(self, start: str, end: str, granularity: str) -> [int]:
index = {
'Year': 4,
'Month': 7,
'Day': 10,
'Hour': 13,
'Minute': 16,
'Second': 19
}[granularity]
start = start[:index]
end = end[:index]
result = []
for id, timestamp in self.logs:
if start <= timestamp[:index] <= end:
result.append(id)
return result
Input: n = 3
Output: 2
def countDerangements(n: int) -> int:
MOD = 10**9 + 7
if n == 0:
return 1
if n == 1:
return 0
dp = [0] * (n + 1)
dp[0], dp[1] = 1, 0
for i in range(2, n + 1):
dp[i] = (i - 1) * (dp[i - 1] + dp[i - 2]) % MOD
return dp[n]
Input: nums = [1,5]
Output: 10
class Solution:
def maxCoins(self, nums: List[int]) -> int:
nums = [1] + nums + [1]
n = len(nums)
@lru_cache(None)
def dp(left: int, right: int) -> int:
if left > right:
return 0
max_coins = 0
for i in range(left, right + 1):
coins = dp(left, i - 1) + dp(i + 1, right) + nums[left - 1] * nums[i] * nums[right + 1]
max_coins = max(max_coins, coins)
return max_coins
return dp(1, n - 2)
Input: forest = [[1,2,3],[0,0,4],[7,6,5]]
Output: 6
Explanation: Following the path above allows you to cut off the trees from shortest to tallest in 6 steps.
class Solution(object):
def cutOffTree(self, forest):
trees = sorted((v, r, c) for r, row in enumerate(forest)
for c, v in enumerate(row) if v > 1)
sr = sc = ans = 0
for _, tr, tc in trees:
d = self.dist(forest, sr, sc, tr, tc)
if d < 0:
return -1
ans += d
sr, sc = tr, tc
return ans
def dist(self, forest, sr, sc, tr, tc):
# Implement the distance function here
return 0
Input: nums = [1,3,5,4,7]
Output: 3
Explanation: The longest continuous increasing subsequence is [1,3,5] with length 3.
Even though [1,3,5,7] is an increasing subsequence, it is not continuous as elements 5 and 7 are separated by element
4.
class Solution:
def findLengthOfLCIS(self, nums: List[int]) -> int:
ans = 0
anchor = 0
for i in range(len(nums)):
if i > 0 and nums[i - 1] >= nums[i]:
anchor = i
ans = max(ans, i - anchor + 1)
return ans
Input: n = 1, presses = 1
Output: 2
Explanation: Status can be:
- [off] by pressing button 1
- [on] by pressing button 2
class Solution:
def findNumberOfLIS(self, nums):
n = len(nums)
length = [1] * n
count = [1] * n
for i in range(n):
for j in range(i):
if nums[j] < nums[i]:
if length[j] + 1 > length[i]:
length[i] = length[j] + 1
count[i] = 0
if length[j] + 1 == length[i]:
count[i] += count[j]
maxLength = max(length)
result = 0
for i in range(n):
if length[i] == maxLength:
result += count[i]
return result
Input: mat1 = [[1,0,0],[-1,0,3]], mat2 = [[7,0,0],[0,0,0],[0,0,1]]
Output: [[7,0,0],[-7,0,3]]
class Solution:
def multiply(self, mat1: List[List[int]], mat2: List[List[int]]) -> List[List[int]]:
n = len(mat1)
k = len(mat1[0])
m = len(mat2[0])
ans = [[0] * m for _ in range(n)]
for rowIndex in range(n):
for elementIndex in range(k):
if mat1[rowIndex][elementIndex] != 0:
for colIndex in range(m):
ans[rowIndex][colIndex] += mat1[rowIndex][elementIndex] * mat2[elementIndex][colIndex]
return ans
Input: n = 1, presses = 1
Output: 2
Explanation: Status can be:
- [off] by pressing button 1
- [on] by pressing button 2
class Solution:
def flipLights(self, n: int, m: int) -> int:
seen = set()
n = min(n, 6)
shift = max(0, 6 - n)
for cand in range(16):
bcount = bin(cand).count('1')
if bcount % 2 == m % 2 and bcount <= m:
lights = 0
if ((cand >> 0) & 1) > 0: lights ^= 0b111111 >> shift
if ((cand >> 1) & 1) > 0: lights ^= 0b010101 >> shift
if ((cand >> 2) & 1) > 0: lights ^= 0b101010 >> shift
if ((cand >> 3) & 1) > 0: lights ^= 0b100100 >> shift
seen.add(lights)
return len(seen)
Input: n = 4, edges = [[1,0],[1,2],[1,3]]
Output: [1]
Explanation: As shown, the height of the tree is 1 when the root is the node with label 1 which is the only MHT.
class Solution:
def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:
if n == 1:
return [0]
from collections import defaultdict, deque
adj = defaultdict(list)
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
leaves = deque()
for i in range(n):
if len(adj[i]) == 1:
leaves.append(i)
remaining_nodes = n
while remaining_nodes > 2:
leaves_size = len(leaves)
remaining_nodes -= leaves_size
for _ in range(leaves_size):
leaf = leaves.popleft()
neighbor = adj[leaf].pop()
adj[neighbor].remove(leaf)
if len(adj[neighbor]) == 1:
leaves.append(neighbor)
return list(leaves)
Input: num = 2736
Output: 7236
Explanation: Swap the number 2 and the number 7.
class Solution:
def maximumSwap(self, num: int) -> int:
A = list(str(num))
ans = A[:]
for i in range(len(A)):
for j in range(i + 1, len(A)):
A[i], A[j] = A[j], A[i]
for k in range(len(A)):
if A[k] != ans[k]:
if A[k] > ans[k]:
ans = A[:]
break
A[i], A[j] = A[j], A[i]
return int(''.join(ans))
Input: prices = [1]
Output: 0
class Solution:
def maxProfit(self, prices: List[int]) -> int:
if not prices:
return 0
n = len(prices)
hold = -prices[0]
sold = 0
cooldown = 0
for i in range(1, n):
new_hold = max(hold, cooldown - prices[i])
new_sold = hold + prices[i]
new_cooldown = max(cooldown, sold)
hold = new_hold
sold = new_sold
cooldown = new_cooldown
return max(sold, cooldown)
Input: root = [1,0,2], low = 1, high = 2
Output: [1,null,2]
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def trimBST(self, root: TreeNode, low: int, high: int) -> TreeNode:
if not root:
return None
if root.val > high:
return self.trimBST(root.left, low, high)
if root.val < low:
return self.trimBST(root.right, low, high)
root.left = self.trimBST(root.left, low, high)
root.right = self.trimBST(root.right, low, high)
return root