267
社区成员
发帖
与我相关
我的任务
分享
哈希表的应用,用哈希表存储出现次数的频率,然后贪心思想就能解决。
class Solution:
def minimumPushes(self, word: str) -> int:
cnt = Counter(word)
arr = list(cnt.values())
arr.sort()
arr.reverse()
return sum(arr[:8])+sum(arr[8:16])*2+sum(arr[16:24])*3+sum(arr[24:26])*4
数据量小,floyd算法
class Solution:
def countOfPairs(self, n: int, x: int, y: int) -> List[int]:
res = [0]*n
dp = [[inf]*(n+1) for _ in range(n+1)]
dp[1][1] = 0
for i in range(2,n+1):
dp[i][i] = 0
dp[i][i-1] = dp[i-1][i] = 1
dp[x][y] = dp[y][x] = 1
def flyd():
for k in range(1,n+1):
for i in range(1,n+1):
for j in range(1,n+1):
dp[i][j] = min(dp[i][j],dp[i][k]+dp[k][j])
flyd()
for i in range(1,n+1):
for j in range(i+1,n+1):
res[dp[i][j]-1] += 1
res[dp[j][i]-1] += 1
return res