2545. 根据第 K 场考试的分数排序
简单二维数组排序,根据给定的k的列次,进行降序排序
class Solution:
def sortTheStudents(self, score: List[List[int]], k: int) -> List[List[int]]:
score.sort(key=lambda s: -s[k])
return score
list.sort(key,reverse)
key:值设置排序方法,或指定list中用于排序的元素reverse:升降序排列,默认为升序排列
>>> a = [('mac', 3, 'b'), ('linux', 2, 'a'), ('mac', 1, 'c')]
>>> a
[('mac', 3, 'b'), ('linux', 2, 'a'), ('mac', 1, 'c')]
>>> a.sort(key=lambda x: x[1]) # lambda 函数:指定用于排序的元素
>>> a
[('mac', 1, 'c'), ('linux', 2, 'a'), ('mac', 3, 'b')]
2545. 根据第 K 场考试的分数排序
灵神小技巧:一般划分和子数组,都是动态规划的技巧
设定f[n]为[0,n-1]的代价最小的拆分子串值,则当我们算f[i+1]时,有动态转移方程:
代码
class Solution:
def minCost(self, nums: List[int], k: int) -> int:
n=len(nums)
f=[0] * (n+1)
for i in range(n):
t=0
cnt=[0] * n
mn=inf
for j in range(i,-1,-1):
x=nums[j]
cnt[x]+=1
if cnt[x]==2:
t+=2
elif cnt[x]>2:
t+=1
if f[j]+t<mn:
mn=f[j]+t
f[i+1]=k+mn
return f[n]