链接: 6188. 按身高排序
定级Easy。
按题意排序即可。
class Solution:
def sortPeople(self, names: List[str], heights: List[int]) -> List[str]:
return [a for a,b in sorted(zip(names,heights),key=lambda x:-x[1])]
定级Medium。
class Solution:
def longestSubarray(self, nums: List[int]) -> int:
n = len(nums)
ans = 1
mx = max(nums)
f = [0]*n
if nums[0] == mx:
f[0] = 1
for i in range(1,n):
if nums[i] == mx:
f[i] = f[i-1]+1
return max(f)
链接: 6190. 找到所有好下标
定级Medium。
class Solution:
def goodIndices(self, nums: List[int], k: int) -> List[int]:
n = len(nums)
f = [1]*n
g = [1]*n
for i in range(1,n):
if nums[i]<=nums[i-1]:
f[i]= f[i-1]+1
if nums[i] >= nums[i-1]:
g[i] = g[i-1]+1
ans = []
for i in range(k,n-k):
if f[i-1] >= k and g[i+k]>=k:
ans.append(i)
return ans
链接: 6191. 好路径的数目
定级Hard。
class Solution:
def numberOfGoodPaths(self, vals: List[int], edges: List[List[int]]) -> int:
p = vals[:]
n = len(vals)
f = [Counter([p[i]]) for i in range(n)]
# print(f)
fathers = list(range(n))
def find_father(x):
if fathers[x] != x:
fathers[x] = find_father(fathers[x])
return fathers[x]
def union(x, y, z):
x = find_father(x)
y = find_father(y)
if x == y:
return 0
fathers[x] = y
a,b = f[y][z],f[x][z]
f[y][z] += f[x][z]
return a*b
g = [[] for _ in range(n)]
for u, v in edges:
g[u].append(v)
g[v].append(u)
vals = sorted([(v, k) for k, v in enumerate(vals)])
vis = set()
ans = 0
# print(vals)
for i in range(n):
v, k = vals[i]
for x in g[k]:
if x in vis:
ans += union(k, x, v)
ans += 1
# x = find_father(k)
# print(f[x][v])
# ans += f[x][v]
vis.add(k)
# ans += n
return ans