if isPalindrome(a) and isPalindrome(b): returnTrue n = len(a)
if n & 1: l = r = n >> 1 else: l, r = (n >> 1) - 1, n >> 1 # print(len(a)) # print(l, r) al, ar = l, r while al >= 0and ar < n and a[al] == a[ar]: al -= 1 ar += 1 bl, br = l, r while bl >= 0and br < n and b[bl] == b[br]: bl -= 1 br += 1 # print(a[:al + 1], b[ar:][::-1]) # print(b[:bl + 1], a[br:][::-1]) return a[:al + 1] == b[ar:][::-1] or b[:bl + 1] == a[br:][::-1] \ or b[:al + 1] == a[ar:][::-1] or a[:bl + 1] == b[br:][::-1]
defcountSubgraphsForEachDiameter(self, n, edges): G = [[] for _ in range(n)] for i, j in edges: G[i - 1].append(j - 1) G[j - 1].append(i - 1)
defmaxd(mask0): res = 0 for i in range(n): if (1 << i) & mask0: mask = mask0 bfs, bfs2 = [i], [] cur = 0 while bfs: for i in bfs: mask ^= 1 << i for j in G[i]: if mask & (1 << j): bfs2.append(j) cur += 1 bfs, bfs2 = bfs2, [] if mask: return0 res = max(res, cur - 1) return res
res = [0] * (n - 1) for mask in range(1 << n): if mask & (mask - 1) == 0: continue d = maxd(mask) if d: res[d - 1] += 1
classSolution: defalertNames(self, keyName: List[str], keyTime: List[str]) -> List[str]: res = set() record = defaultdict(list) for name, time in zip(keyName, keyTime): if name in res: continue tmp = self.to_minute(time) loc = bisect.bisect_left(record[name], tmp) record[name].insert(loc, tmp) if loc - 2 >= 0and tmp - record[name][loc - 2] <= 60: res.add(name) continue if loc - 1 >= 0and loc + 1 < len(record[name]) and record[name][ loc + 1] - record[name][loc - 1] <= 60: res.add(name) continue if loc + 2 < len(record[name]) and record[name][loc + 2] - tmp <= \ 60: res.add(name) continue res = list(res) res.sort() return res
defto_minute(self, time_str): h, m = map(int, time_str.split(":")) return h * 60 + m
5518. 给定行和列的和求可行矩阵
1 2 3 4 5 6 7 8 9 10 11 12
classSolution: defrestoreMatrix(self, rowSum: List[int], colSum: List[int]) -> List[List[int]]: m = len(rowSum) n = len(colSum) res = [[0] * n for _ in range(m)] for i in range(m): for j in range(n): res[i][j] = min(rowSum[i], colSum[j]) rowSum[i] -= res[i][j] colSum[j] -= res[i][j] return res
classSolution: defbusiestServers(self, ks: int, a: List[int], d: List[int]) -> List[int]: from sortedcontainers import SortedList ans = [0] * ks pq = [] fu = SortedList(range(ks)) v = 0 for i, j in zip(a, d): heappush(pq, [i, 1, i + j, v]) v += 1 # print(pq,fu) while pq: i, k, j, num = heappop(pq) if k == 1and fu: v = fu.bisect_left(num % ks) if v == len(fu): v = 0 v = fu[v] fu.remove(v) ans[v] += 1 heappush(pq, [j, 0, v, num]) elif k == 0: fu.add(j) # print(pq,fu) # print(ans) t = max(ans) return [i for i in range(ks) if ans[i] == t]
classSolution: defspecialArray(self, nums: List[int]) -> int: n = len(nums) for i in range(n + 1): c = 0 for num in nums: if num >= i: c += 1 if c == i: return i return-1
classSolution: defisEvenOddTree(self, root: TreeNode) -> bool: q, nq = [root], [] flag = True while q: if flag: pre = float('-inf') for node in q: if node.val & 1 == 0or node.val <= pre: returnFalse pre = node.val if node.left: nq.append(node.left) if node.right: nq.append(node.right) else: pre = float('inf') for node in q: if node.val & 1 == 1or node.val >= pre: returnFalse pre = node.val if node.left: nq.append(node.left) if node.right: nq.append(node.right) q, nq = nq, [] flag = not flag returnTrue
classSolution: defvisiblePoints(self, points: List[List[int]], angle: int, location: List[int]) -> int: import math angle = angle / 360 * 2 * math.pi cnt = 0 a = [] for x, y in points: if x == location[0] and y == location[1]: cnt += 1 else: xx, yy = x - location[0], y - location[1] a.append(math.atan2(yy, xx)) a.sort() n = len(a) b = [x + math.pi * 2for x in a] a += b j = 0
ret = 0 for i in range(n): while j < len(a): if a[j] - a[i] > angle: break j += 1 ret = max(ret, j - i) return ret + cnt
5533. 使整数变为 0 的最少操作次数
1 2 3 4 5 6 7
classSolution: defminimumOneBitOperations(self, n: int) -> int: ans = 0 while n: ans ^= n n >>= 1 return ans
1 2 3 4 5 6
classSolution: defminimumOneBitOperations(self, n: int) -> int: if n == 0: return0 p = n.bit_length() return (1 << p) - 1 - self.minimumOneBitOperations(n - (1 << (p - 1)))
classSolution: defminOperations(self, logs: List[str]) -> int: cur = 0 for log in logs: if log == '../': if cur: cur -= 1 elif log == './': continue else: cur += 1 return cur
classSolution: defminOperationsMaxProfit(self, customers: List[int], boardingCost: int, runningCost: int) -> int: ans = 0 res = 0 p = 0 w = 0 i = 0 for c in customers: i += 1 w += c b = min(w, 4) w -= b p += b * boardingCost - runningCost if p > res: res = p ans = i while w: i += 1 b = min(w, 4) w -= b p += b * boardingCost - runningCost if p > res: res = p ans = i return ans if ans else-1
defgetInheritanceOrder(self) -> List[str]: res = [] stack = [self.root] while stack: node = stack.pop() ifnot node.is_death: res.append(node.name) for child in reversed(node.children): stack.append(child) return res
classSolution { int tot[25]; public: intmaximumRequests(int n, vector<vector<int>> &req){ int ans = 0; int m = req.size(); int lim = (1 << m) - 1; for (int i = 1; i <= lim; ++i) { for (int j = 0; j < n; ++j) tot[j] = 0; int cnt = 0; for (int j = 0, k = 1; j < m; ++j, k <<= 1) if (i & k) { ++tot[req[j][1]], --tot[req[j][0]]; ++cnt; } bool flag = true; for (int j = 0; j < n; ++j) { if (tot[j] != 0) { flag = false; break; } } if (flag) ans = max(ans, cnt); } return ans; } };
classSolution { public: /** * @param words: a set of stirngs * @param target: a target string * @param k: An integer * @return: output all the strings that meet the requirements */
intminDistance(string word1, string word2, int k){ int m = word1.size(); int n = word2.size(); if (m - n > k || n - m > k) return k + 1; vector<vector<int>> dp(m + 1, vector<int>(n + 1)); for (int i = 0; i <= m; i++) { dp[i][0] = i; } for (int j = 0; j <= n; j++) { dp[0][j] = j; } for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) { if (word1[i - 1] == word2[j - 1]) dp[i][j] = dp[i - 1][j - 1]; else { dp[i][j] = 1 + min(dp[i - 1][j - 1], min(dp[i][j - 1], dp[i - 1][j])); } } } return dp[m][n]; }
vector<string> kDistance(vector<string> &words, string &target, int k){ // write your code here vector<string> res; for (auto &word: words) { if (minDistance(word, target, k) <= k) { res.push_back(word); } } return res; } };
2. 折纸
描述
折纸,每次都是将纸从右向左对折,凹痕为 0,凸痕为 1,求折 n 次后,将纸展开所得折痕组成的 01 序列。
classSolution: """ @param n: The folding times @return: the 01 string """
defgetString(self, n): # Write your code here defprintProcess(i, N, down): if i > N: return printProcess(i + 1, N, True) if down isTrue: res.append('0') else: res.append('1') printProcess(i + 1, N, False)
res = [] printProcess(1, n, True) return"".join(res)
classSolution: """ @param str: A string @return: all permutations """
defstringPermutation(self, s): # write your code here li = list(s) li.sort() q, nq = [""], [] for char in li: for ans in q: for i in range(len(ans), -1, -1): if i < len(ans) and char == ans[i]: break nq.append(ans[:i] + char + ans[i:]) q, nq = nq, [] q.sort() return q
classSolution: """ @param values: a vector of integers @return: a boolean which equals to true if the first player will win """
deffirstWillWin(self, values): # write your code here n = len(values) dp = [[[0, 0] for _ in range(n)] for _ in range(n)] for i in range(n): dp[i][i][0] = values[i] for gap in range(1, n): for i in range(n - gap): j = i + gap left = dp[i + 1][j][1] + values[i] right = dp[i][j - 1][1] + values[j] if left > right: dp[i][j][0] = left dp[i][j][1] = dp[i + 1][j][0] else: dp[i][j][0] = right dp[i][j][1] = dp[i][j - 1][0] return dp[0][n - 1][0] > dp[0][n - 1][1]
voidinsertion_sort(vector<int>& A){ for (int i = 1; i < A.size(); ++i) { int key = A[i]; int j = i - 1; while (j >= 0 && A[j] > key) { A[j + 1] = A{j}; --j; } A[j + 1] = key; } }
voidbucket_sort(){ int bucket_size = w / n + 1; for (int i = 0; i < n; ++i) { bucket[i].clear(); } for (int i = 1; i <= n; ++i) { bucket[a[i] / bucket_size].push_back(a[i]); } int p = 0; for (int i = 0; i < n; ++i) { insertion_sort(bucket[i]); for (int j = 0; k < bucket[i].size() ++j) { a[++p] = bucket[i][j]; } } }
voidmax_heapify(int arr[], int start, intend){ // 建立父结点指标和子结点指标 int dad = start; int son = dad * 2 + 1; while (son <= end) { // 子结点指标在范围内才做比较 if (son + 1 <= end && arr[son] < arr[son + 1]) // 先比较两个子结点大小,选择最大的 son++; if (arr[dad] > arr[son]) // 如果父结点比子结点大,代表调整完毕,直接跳出函数 return; else { // 否则交换父子内容,子结点再和孙结点比较 swap(arr[dad], arr[son]); dad = son; son = dad * 2 + 1; } } }
voidheap_sort(int arr[], int len){ // 初始化,i从最后一个父结点开始调整 for (int i = len / 2 - 1; i >= 0; i--) max_heapify(arr, i, len - 1); // 先将第一个元素和已经排好序的元素前一位做交换,再重新调整(刚调整的元素之前的元素),直到排序完毕 for (int i = len - 1; i > 0; i--) { swap(arr[0], arr[i]); max_heapify(arr, 0, i - 1); } }