class Solution:
def minimumOperations(self, nums: List[int]) -> int:
return len([x for x in set(nums) if x > 0])
链接: 2358. 分组的最大数量
class Solution:
def maximumGroups(self, gs: List[int]) -> int:
gs.sort()
n = len(gs)
presum = accumulate(gs,initial=0)
size = 2
step = 1
ans = 1
print(step,size,n)
while step+size <= n:
step += size
size += 1
ans+=1
# print(step,size,n,ans)
return ans
定级Medium。
class Solution:
def closestMeetingNode(self, es: List[int], node1: int, node2: int) -> int:
g= defaultdict(list)
n = len(es)
for i,e in enumerate(es):
if e != -1:
g[i].append(e)
path1 = {}
visited1 = defaultdict(int)
visited1[node1] = 1
# path1[node1] = 0
q = deque([node1])
while q:
u = q.popleft()
depth = visited1[u]+1
for v in g[u]:
if not visited1[v]:
visited1[v] = depth
q.append(v)
visited2 = defaultdict(int)
q = deque([node2])
visited2[node2] = 1
while q :
u = q.popleft()
depth = visited2[u] + 1
for v in g[u]:
if not visited2[v]:
visited2[v] = depth
q.append(v)
# print(visited1,visited2)
ans,d = inf,inf
for k,v in visited1.items():
if k in visited2:
m = max(v,visited2[k])
if m < d:
d = m
ans = k
if m == d:
ans = min(ans,k)
# print(k,v,visited2[k],ans,d)
return ans if ans != inf else -1
链接: 2360. 图中的最长环
定级Hard。
class Solution:
def longestCycle(self, edges: List[int]) -> int:
n = len(edges)
g = defaultdict(list)
for i,e in enumerate(edges):
if e != -1:
g[i].append(e)
visited = [0] * n
ma = -1
path = []
def dfs(u):
visited[u] = 1
path.append(u)
for v in g[u]:
if visited[v] == 0:
dfs(v)
if visited[v] == 1:
# print('环')
cnt = 0
for j in path[::-1]:
cnt += 1
if j == v:
break
nonlocal ma
if cnt > ma:
ma = cnt
visited[u] = -1
path.pop()
for i in range(n):
if visited[i] > -1:
dfs(i)
return ma