# coding:utf-8 # Copyright (C) dirlt from typing import List from collections import Counter, defaultdict, deque from functools import lru_cache import heapq class Solution: def minOperations(self, nums: List[int]) -> int: ans = 0 x = nums[0] for i in range(1, len(nums)): y = nums[i] to = max(x + 1, y) ans += to - y x = to return ans cases = [ ([1, 5, 2, 4, 1], 14), ] import aatest_helper aatest_helper.run_test_cases(Solution().minOperations, cases) if __name__ == '__main__': pass
import functools @functools.lru_cache(maxsize=None) def dfs(i, j, d): if i == n or j == m: return False c = grid[i][j] d += (1 if c == '(' else -1) if d < 0: return False if (i, j) == (n - 1, m - 1): return d == 0 return dfs(i + 1, j, d) or dfs(i, j + 1, d) return dfs(0, 0, 0) true, false, null = True, False, None cases = [ ([["(", "(", "("], [")", "(", ")"], ["(", "(", ")"], ["(", "(", ")"]], true), ([[")", ")"], ["(", "("]], false), ] import aatest_helper aatest_helper.run_test_cases(Solution().hasValidPath, cases) if __name__ == '__main__': pass
for w in words: for i in range(len(w)): c = ord(w[i]) - ord('a') indices[c][i] += 1 dp = [[0] * (sz + 1) for _ in range(n + 1)] dp[0][0] = 1 for i in range(n): acc = 0 for k in range(sz): acc += dp[i][k] occ = indices[target[i]][k] dp[i + 1][k + 1] = acc * occ ans = sum(dp[n]) return ans % MOD cases = [ (["acca", "bbbb", "caca"], "aba", 6), (["abba", "baab"], "bab", 4), (["abcd"], "abcd", 1), (["abab", "baba", "abba", "baab"], "abba", 16), ] import aatest_helper aatest_helper.run_test_cases(Solution().numWays, cases) aatest_helper.run_test_cases(Solution2().numWays, cases)
class Solution: def findRightInterval(self, intervals: List[List[int]]) -> List[int]: ss = [(intervals[i][0], i) for i in range(len(intervals))] ss.sort() xs = [x[0] for x in ss] ys = [x[1] for x in ss] # 如果这里要求解最小下标的话,可以使用它处理 # for i in reversed(range(1, len(ys))): # ys[i-1] = min(ys[i-1], ys[i]) ans = [] for s, e in intervals: import bisect idx = bisect.bisect_left(xs, e) if 0 <= idx < len(ys): ans.append(ys[idx]) else: ans.append(-1) return ans cases = [([[1, 2]], [-1]), ([[3, 4], [2, 3], [1, 2]], [-1, 0, 1]), ([[1, 4], [2, 3], [3, 4]], [-1, 2, -1])] import aatest_helper aatest_helper.run_test_cases(Solution().findRightInterval, cases)
lastIndex = -1 ans = [] while True: index = -1 for i in reversed(range(26)): if count[i] != 0 and i != lastIndex: index = i break if index == -1: break used = min(count[index], repeatLimit) if lastIndex > index and count[lastIndex]: used = 1 ans.extend([index] * used) count[index] -= used lastIndex = index ans = ''.join((chr(x + ord('a')) for x in ans)) return ans true, false, null = True, False, None cases = [("cczazcc", 3, "zzcccac"), ("aababab", 2, "bbabaa")] import aatest_helper aatest_helper.run_test_cases(Solution().repeatLimitedString, cases) if __name__ == '__main__': pass
# 但是此时 lhp.top() 可能会 > rhp.top() # 如果是这种情况的话,需要交换顶层两个元素 if rhp.top() and lhp.top()[0] > rhp.top()[0]: (rv, ridx) = rhp.top() assert indices[ridx][0] == 1 hridx = indices[ridx][1] (lv, lidx) = lhp.top() assert indices[lidx][0] == 0 hlidx = indices[lidx][1] lhp.set_index(hlidx, (rv, ridx)) indices[ridx] = (0, hlidx) rhp.set_index(hridx, (lv, lidx)) indices[lidx] = (1, hridx) # print(indices) # print(i, median()) ans.append(median()) return ans cases = [ ([1, 2], 1, [1, 2]), ([1, 3, -1, -3, 5, 3, 6, 7], 3, [1, -1, -1, 3, 5, 6]), ([-1, -3, 5, 3], 3, [-1, 3]), ] import aatest_helper aatest_helper.run_test_cases(Solution().medianSlidingWindow, cases)
cross[nums2[i]].append(i) seq = [(-1, -1)] for k, xs in cross.items(): if len(xs) == 2: seq.append(xs) seq.append((n - 1, m - 1)) ans = 0 for j in range(1, len(seq)): a, b = seq[j - 1][0] + 1, seq[j][0] c, d = seq[j - 1][1] + 1, seq[j][1] # sum(nums1[a+1 .. b]), sum(nums2[c+1 .. d]) t0 = acc1[b] - (acc1[a - 1] if a != 0 else 0) t1 = acc2[d] - (acc2[c - 1] if c != 0 else 0) ans += max(t0, t1) MOD = 10 ** 9 + 7 ans = ans % MOD return ans cases = [ ([2, 4, 5, 8, 10], [4, 6, 8, 9], 30), ([1, 4, 5, 8, 9, 11, 19], [2, 3, 4, 11, 12], 61), ([1, 2, 3, 4, 5], [6, 7, 8, 9, 10], 40), ([1, 3, 5, 7, 9], [3, 5, 100], 109), ] import aatest_helper aatest_helper.run_test_cases(Solution().maxSum, cases)
exp = d + i heapq.heappush(hp, (exp, a)) while hp: (exp, a) = heapq.heappop(hp) if i >= exp: continue a -= 1 ans += 1 if a: heapq.heappush(hp, (exp, a)) break i = len(apples) while hp: (exp, a) = heapq.heappop(hp) if i >= exp: continue eat = min((exp - i), a) i += eat ans += eat return ans import aatest_helper cases = [ ([1, 2, 3, 5, 2], [3, 2, 1, 4, 2], 7), ([3, 0, 0, 0, 0, 2], [3, 0, 0, 0, 0, 2], 5), ] aatest_helper.run_test_cases(Solution().eatenApples, cases)
# Copyright (C) dirlt class Solution: def reorderSpaces(self, text: str) -> str: ss = [x.strip() for x in text.split()] blk = 0 for c in text: if c == ' ': blk += 1 n = len(ss) if n == 1: avg = 0 else: avg = blk // (n - 1) rmd = blk - (n - 1) * avg ans = (' ' * avg).join(ss) + ' ' * rmd return ans cases = [ (" this is a sentence ", "this is a sentence"), (" practice makes perfect", "practice makes perfect "), ("hello world", "hello world"), (" walks udp package into bar a", "walks udp package into bar a "), ("a", "a"), ] import aatest_helper aatest_helper.run_test_cases(Solution().reorderSpaces, cases)
m = (s + e) // 2 if arr[m] >= i: e = m - 1 else: s = m + 1 res += (len(arr) - s) # print(i, R[exp], L[exp], res) ans = max(ans, res) return ans true, false, null = True, False, None cases = [ ([2, -1, 2], 3, 1), ([0, 0, 0], 1, 2), ([22, 4, -25, -20, -15, 15, -16, 7, 19, -10, 0, -13, -14], -33, 4), ([ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 30827, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], 0, 33), ] import aatest_helper aatest_helper.run_test_cases(Solution().waysToPartition, cases) if __name__ == '__main__': pass
for y, dt in adj[x]: if (t + dt) > maxTime: continue path.append(y) visited[y] += 1 res2 = res if visited[y] == 1: res2 += values[y] dfs(y, t + dt, res2) visited[y] -= 1 path.pop() visited[0] = 1 dfs(0, 0, values[0]) return ans[0] true, false, null = True, False, None cases = [ ([0, 32, 10, 43], [[0, 1, 10], [1, 2, 15], [0, 3, 10]], 49, 75), ([5, 10, 15, 20], [[0, 1, 10], [1, 2, 10], [0, 3, 10]], 30, 25), ([1, 2, 3, 4], [[0, 1, 10], [1, 2, 11], [2, 3, 12], [1, 3, 13]], 50, 7), ] import aatest_helper aatest_helper.run_test_cases(Solution().maximalPathQuality, cases) if __name__ == '__main__': pass
buf.append(w) ans.append(flush(wc, buf, ending=True)) return ans cases = [ (["This", "is", "an", "example", "of", "text", "justification."], 16, [ "This is an", "example of text", "justification. " ]), (["What", "must", "be", "acknowledgment", "shall", "be"], 16, [ "What must be", "acknowledgment ", "shall be " ]), (["Science", "is", "what", "we", "understand", "well", "enough", "to", "explain", "to", "a", "computer.", "Art", "is", "everything", "else", "we", "do"], 20, [ "Science is what we", "understand well", "enough to explain to", "a computer. Art is", "everything else we", "do " ]) ] import aatest_helper aatest_helper.run_test_cases(Solution().fullJustify, cases)
class Solution: def rangeSumBST(self, root: TreeNode, L: int, R: int) -> int: def fn(root): if root is None: return 0 ans = 0 if root.val < L: ans += fn(root.right) elif root.val > R: ans += fn(root.left) else: ans += root.val ans += fn(root.right) ans += fn(root.left) return ans ans = fn(root) return ans null = None cases = [ (aatest_helper.list_to_tree([10, 5, 15, 3, 7, null, 18]), 7, 15, 32), (aatest_helper.list_to_tree([10, 5, 15, 3, 7, 13, 18, 1, null, 6]), 6, 10, 23) ] sol = Solution() aatest_helper.run_test_cases(sol.rangeSumBST, cases)
src_idxs = set([i for i in range(n) if S in my_routes[i]]) dst_idxs = set([i for i in range(n) if T in my_routes[i]]) # 如果存在交集的话,那么不用任何换乘 if src_idxs & dst_idxs: return 1 sts = [(i, j) for i in src_idxs for j in dst_idxs] res = (n + 1) for s, t in sts: val = shortest_path(s, t) if val != -1: res = min(res, val) if res == (n + 1): return -1 return res + 1 cases = [ ([[1, 2, 7], [3, 6, 7]], 1, 6, 2), ([[1, 2, 3], [3, 4, 5], [4, 5, 6]], 1, 6, 3), ([[1, 2, 3], [3, 4, 5], [4, 5, 6], [2, 3, 6]], 1, 6, 2), ([[1, 2, 3]], 1, 4, -1), ([[1, 7], [3, 5]], 5, 5, 0), # aatest_helper.read_case_from_file('/Users/dirlt/playbook/input.in', 1), ] sol = Solution() aatest_helper.run_test_cases(sol.numBusesToDestination, cases)
continue idx = i forward = nums[idx] > 0 initiator = idx while nums[idx] != 0: t = (idx + nums[idx] + n) % n marker[idx] = initiator nums[idx] = 0 traces[idx] = trace_id trace_id += 1 idx = t if forward != (nums[idx] > 0): break if nums[idx] == 0 and marker[idx] == initiator: if (trace_id - traces[idx]) > 1: return True return False import aatest_helper cases = (([2, -1, 1, 2, 2], True), ([-1, 2], False), ([-1, -2, -3, -4, -5], False), ([-2, 1, -1, -2, -2], False), ([1, 1, 2], True)) aatest_helper.run_test_cases(Solution().circularArrayLoop, cases)
if x == X: return c y = x + a # 这个上限有点不太好确定!! if y < 4000: if y not in forbidden and y not in visited: visited.add(y) heapq.heappush(hp, (y, c + 1, 1)) if d == 1 and x >= b: y = x - b if y not in forbidden and y not in visited: visited.add(y) heapq.heappush(hp, (y, c + 1, 0)) return -1 cases = [ ([14, 4, 18, 1, 15], 3, 15, 9, 3), ([8, 3, 16, 6, 12, 20], 15, 13, 11, -1), ([1, 6, 2, 14, 5, 17, 4], 16, 9, 7, 2), ([162, 118, 178, 152, 167, 100, 40, 74, 199, 186, 26, 73, 200, 127, 30, 124, 193, 84, 184, 36, 103, 149, 153, 9, 54, 154, 133, 95, 45, 198, 79, 157, 64, 122, 59, 71, 48, 177, 82, 35, 14, 176, 16, 108, 111, 6, 168, 31, 134, 164, 136, 72, 98], 29, 98, 80, 121), ] import aatest_helper aatest_helper.run_test_cases(Solution().minimumJumps, cases)
@functools.lru_cache(maxsize=None) def get_values(t): xs = [(value(x[-t:]), i) for (i, x) in enumerate(nums)] xs.sort() return xs def doquery(k, t): xs = get_values(t) # print(xs, k) return xs[k - 1][1] ans = [] for k, t in queries: r = doquery(k, t) ans.append(r) return ans true, false, null = True, False, None cases = [(["102", "473", "251", "814"], [[1, 1], [2, 3], [4, 2], [1, 2]], [2, 2, 1, 0]), (["24", "37", "96", "04"], [[2, 1], [2, 2]], [3, 0])] import aatest_helper aatest_helper.run_test_cases(Solution().smallestTrimmedNumbers, cases) if __name__ == '__main__': pass
class Solution: def removeSubfolders(self, folder: List[str]) -> List[str]: folder.sort() def is_prefix(a, b): if len(a) < len(b): return a == b[:len(a)] and b[len(a)] == '/' return False pfx = '-' ans = [] for s in folder: if is_prefix(pfx, s): continue else: pfx = s ans.append(pfx) return ans cases = [ (["/a", "/a/b", "/c/d", "/c/d/e", "/c/f"], ["/a", "/c/d", "/c/f"]) ] import aatest_helper aatest_helper.run_test_cases(Solution().removeSubfolders, cases)
class Solution: def permute(self, nums: List[int]) -> List[List[int]]: ans = [] nums.sort() n = len(nums) used = [False] * n def dfs(path): if len(path) == n: ans.append(path.copy()) return for j in range(n): if not used[j]: used[j] = True path.append(nums[j]) dfs(path) path.pop() used[j] = False dfs([]) return ans cases = [([1, 2, 3], [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]])] import aatest_helper aatest_helper.run_test_cases(Solution().permute, cases)
while stone: j -= 1 stone -= 1 ans[j][i] = '#' for i in range(n): stone = 0 for j in range(m): if box[i][j] == '#': stone += 1 elif box[i][j] == '*': flush(n - 1 - i, j, stone) stone = 0 flush(n - 1 - i, m, stone) return ans cases = [ ([["#", ".", "#"]], [["."], ["#"], ["#"]]), ([["#", ".", "*", "."], ["#", "#", "*", "."]], [["#", "."], ["#", "#"], ["*", "*"], [".", "."]]) ] import aatest_helper aatest_helper.run_test_cases(Solution().rotateTheBox, cases) if __name__ == '__main__': pass
class Solution: def isPossible(self, nums: List[int]) -> bool: import heapq from collections import defaultdict last = defaultdict(list) for x in nums: # query last pq = last[x - 1] y = heapq.heappop(pq) if pq else 0 heapq.heappush(last[x], y + 1) for x, pq in last.items(): if pq and pq[0] < 3: return False return True cases = [ ([1, 2, 3, 3, 4, 5], True), ([1, 2, 3, 3, 4, 4, 5, 5], True), ([1, 2, 3, 4, 4, 5], False), ] import aatest_helper aatest_helper.run_test_cases(Solution().isPossible, cases)
x = nums[i] heapq.heappush(hp, x) y = heapq.heappop(hp) tt = tt - y + x right.append(max(right[-1], tt)) return right[::-1] left = process_left(nums) right = process_right(nums) print(left, right) ans = 1 << 63 for i in range(len(left)): res = left[i] - right[i] ans = min(ans, res) return ans true, false, null = True, False, None cases = [ ([3, 1, 2], -1), ([7, 9, 5, 8, 1, 3], 1), ] import aatest_helper aatest_helper.run_test_cases(Solution().minimumDifference, cases) if __name__ == '__main__': pass
back_rec = True if back_rec: ans = [] def dfs(v, path, d): if depth[v] > d: return if v == begin: ans.append([wordList[i] for i in reversed(path)]) return for t in back_links[v]: path.append(t) dfs(t, path, d - 1) path.pop() dfs(end, [end], depth[end]) return ans cases = [("hit", "cog", ["hot", "dot", "dog", "lot", "log", "cog"], [["hit", "hot", "dot", "dog", "cog"], ["hit", "hot", "lot", "log", "cog"]]), ("a", "c", ["a", "b", "c"], [["a", "c"]])] import aatest_helper aatest_helper.run_test_cases(Solution().findLadders, cases)
adj[i].add(j) adj[j].add(i) mask = set() def dfs(x): mask.add(x) for y in adj[x]: if y not in mask: dfs(y) t = 0 for i in range(N): if i in mask: continue t += 1 dfs(i) return t <= n true, false, null = True, False, None cases = [([[0, 1, 3], [1, 0, 3], [3, 3, 0]], 2, true), ([[0, 3, 3], [3, 0, 3], [3, 3, 0]], 2, false), ([[0, 3, 1, 4], [3, 0, 1, 3], [1, 1, 0, 5], [4, 3, 5, 0]], 2, true)] import aatest_helper aatest_helper.run_test_cases(Solution().isCompliance, cases) if __name__ == '__main__': pass
if x0 < x1: res = [x + s[idx] for x in y0] cost = x0 elif x0 > x1: res = y1 cost = x1 else: res = [x + s[idx] for x in y0] + y1 cost = x0 pass else: cost, res = run(idx - 1, depth) res = [x + s[idx] for x in res] dp[key] = (cost, res) return cost, res cost, res = run(idx=len(s) - 1, depth=0) ans = list(set(res)) # print(cost, ans) return ans cases = [("()())()", ["()()()", "(())()"]), (")(", [""]), ("(a)())()", ["(a)()()", "(a())()"])] import aatest_helper aatest_helper.run_test_cases(Solution().removeInvalidParentheses, cases)
def ok(x): cnt = [0] * 10 while x: y = x % 10 cnt[y] += 1 if cnt[y] > y: return False x = x // 10 for i in range(1, 10): if cnt[i] != 0 and cnt[i] != i: return False return True n += 1 while not ok(n): n += 1 return n true, false, null = True, False, None cases = [(1, 22), (1000, 1333), (3000, 3133)] import aatest_helper aatest_helper.run_test_cases(Solution().nextBeautifulNumber, cases) if __name__ == '__main__': pass
# 确保orders的数量 == ind的数量,这意味着没有环 if len(orders) != len(ind): return "" ans = list(chars) def cmpfn(x, y): if x in orders and y in orders: return orders[x] - orders[y] else: return ord(x) - ord(y) import functools ans.sort(key=functools.cmp_to_key(cmpfn)) ans = ''.join(ans) return ans cases = [(["wrt", "wrf", "er", "ett", "rftt"], "wertf"), (["z", "x"], "zx"), (["zy", "zx"], "yxz"), (["ay", "ax"], "ayx"), (["abc", "bcd", "qwert", "ab"], ""), ([ "ze", "yf", "xd", "wd", "vd", "ua", "tt", "sz", "rd", "qd", "pz", "op", "nw", "mt", "ln", "ko", "jm", "il", "ho", "gk", "fa", "ed", "dg", "ct", "bb", "ba" ], "zyxwvutsrqponmlkjihgfedcba")] import aatest_helper aatest_helper.run_test_cases(Solution().alienOrder, cases)
j = 0 c = 1 for i in range(len(position)): if (position[i] - position[j]) < k: continue j = i c += 1 return c >= m s, e = 0, position[-1] - position[0] while s <= e: k = (s + e) // 2 ok = isOK(k) # print(k, ok) if ok: s = k + 1 else: e = k - 1 ans = e return ans cases = [ ([1, 2, 3, 4, 7], 3, 3), ([5, 4, 3, 2, 1, 1000000000], 2, 999999999), ] import aatest_helper aatest_helper.run_test_cases(Solution().maxDistance, cases)
s = m + 1 elif (m + 1) < n and nums[m] == nums[m + 1]: sz = e - (m + 2) + 1 if sz % 2 == 1: s = m + 2 else: e = m - 1 else: return nums[m] assert s == e return nums[s] cases = [([1, 1, 2, 3, 3, 4, 4, 8, 8], 2), ( [3, 3, 7, 7, 10, 11, 11], 10, ), ([ 1, 1, 2, 3, 3, ], 2)] import aatest_helper aatest_helper.run_test_cases(Solution2().singleNonDuplicate, cases)
# D是用来比较每个字符的权重的 hp = [(v, k) for k, v in ws.items()] import heapq heapq.heapify(hp) while hp: (v, k) = heapq.heappop(hp) ans.append(k) ans = ''.join(ans) return ans cases = [ (["ABC", "ACB", "ABC", "ACB", "ACB"], "ACB"), (["BCA", "CAB", "CBA", "ABC", "ACB", "BAC"], "ABC"), (["M", "M", "M", "M"], "M"), (["ZMNAGUEDSJYLBOPHRQICWFXTVK"], "ZMNAGUEDSJYLBOPHRQICWFXTVK"), (["WXYZ", "XYZW"], "XWYZ"), (["FVSHJIEMNGYPTQOURLWCZKAX", "AITFQORCEHPVJMXGKSLNZWUY", "OTERVXFZUMHNIYSCQAWGPKJL", "VMSERIJYLZNWCPQTOKFUHAXG", "VNHOZWKQCEFYPSGLAMXJIUTR", "ANPHQIJMXCWOSKTYGULFVERZ", "RFYUXJEWCKQOMGATHZVILNSP", "SCPYUMQJTVEXKRNLIOWGHAFZ", "VIKTSJCEYQGLOMPZWAHFXURN", "SVJICLXKHQZTFWNPYRGMEUAO", "JRCTHYKIGSXPOZLUQAVNEWFM", "NGMSWJITREHFZVQCUKXYAPOL", "WUXJOQKGNSYLHEZAFIPMRCVT", "PKYQIOLXFCRGHZNAMJVUTWES", "FERSGNMJVZXWAYLIKCPUQHTO", "HPLRIUQMTSGYJVAXWNOCZEKF", "JUVWPTEGCOFYSKXNRMHQALIZ", "MWPIAZCNSLEYRTHFKQXUOVGJ", "EZXLUNFVCMORSIWKTYHJAQPG", "HRQNLTKJFIEGMCSXAZPYOVUW", "LOHXVYGWRIJMCPSQENUAKTZF", "XKUTWPRGHOAQFLVYMJSNEIZC", "WTCRQMVKPHOSLGAXZUEFYNJI"], "VWFHSJARNPEMOXLTUKICZGYQ") ] import aatest_helper aatest_helper.run_test_cases(Solution().rankTeams, cases)