现在你需要从两个不同的数组中选择两个整数(每个数组选一个)并且计算它们的距离。两个整数 a 和 b 之间的距离定义为它们差的绝对值 |a-b| 。
返回最大距离。
涉及知识点
数学
解决思路
秒答题。
1 2 3 4 5 6 7 8 9 10
classSolution: defmaxDistance(self, arrays: List[List[int]]) -> int: big=-inf small=inf ans=-inf for each in arrays: ans=max(ans,each[-1]-small,big-each[0]) big=max(big,each[-1]) small=min(small,each[0]) return ans
classSolution: defmaximumSubsequenceCount(self, text: str, pattern: str) -> int: x,y=pattern ans=cnt_x=cnt_y=0 for c in text: if c==y: ans+=cnt_x cnt_y+=1 if c==x: cnt_x+=1 return ans+max(cnt_x,cnt_y)
3285.找到稳定山的下标(1166)
有 n 座山排成一列,每座山都有一个高度。给你一个整数数组 height ,其中 height[i] 表示第 i 座山的高度,再给你一个整数 threshold 。
classSolution: defstableMountains(self, height: List[int], threshold: int) -> List[int]: ans=[] for i,value inenumerate(height): if value>threshold and i<len(height)-1: ans.append(i+1) return ans
633.平方数之和(中等)
给定一个非负整数 c ,你要判断是否存在两个整数 a 和 b,使得 a2 + b2 = c 。
涉及知识点
数学
解决思路
秒答题,while循环。
1 2 3 4 5 6 7 8 9
classSolution: defjudgeSquareSum(self, c: int) -> bool: a=0 while a*a*2<=c: b=isqrt(c-a*a) if a*a+b*b==c: returnTrue a+=1 returnFalse
1705.吃苹果的最大数目(1930)
有一棵特殊的苹果树,一连 n 天,每天都可以长出若干个苹果。在第 i 天,树上会长出 apples[i] 个苹果,这些苹果将会在 days[i] 天后(也就是说,第 i + days[i] 天时)腐烂,变得无法食用。也可能有那么几天,树上不会长出新的苹果,此时用 apples[i] == 0 且 days[i] == 0 表示。
classSolution: defeatenApples(self, apples: List[int], days: List[int]) -> int: ans = 0 h = [] for i, (num, day) inenumerate(zip(apples, days)): while h and h[0][0] == i: # 已腐烂 heappop(h) if num: heappush(h, [i + day, num]) if h: ans += 1 h[0][1] -= 1# 吃一个最早腐烂的苹果 if h[0][1] == 0: heappop(h)
i = len(apples) whileTrue: while h and h[0][0] <= i: # 已腐烂 heappop(h) ifnot h: return ans rotten_day, num = heappop(h) k = min(num, rotten_day - i) ans += k i += k
classSolution: defnetworkDelayTime(self, times: List[List[int]], n: int, k: int) -> int: g = [[inf for _ inrange(n)] for _ inrange(n)] # 邻接矩阵 for x, y, d in times: g[x - 1][y - 1] = d
dis = [inf] * n ans = dis[k - 1] = 0 done = [False] * n whileTrue: x = -1 for i, ok inenumerate(done): ifnot ok and (x < 0or dis[i] < dis[x]): x = i if x < 0: return ans # 最后一次算出的最短路就是最大的 if dis[x] == inf: # 有节点无法到达 return -1 ans = dis[x] # 求出的最短路会越来越大 done[x] = True# 最短路长度已确定(无法变得更小) for y, d inenumerate(g[x]): # 更新 x 的邻居的最短路 dis[y] = min(dis[y], dis[x] + d)