classSolution: defminimumAbsDifference(self, arr: List[int]) -> List[List[int]]: min_abs = 10**7 arr.sort() ans = [] for i inrange(0, len(arr)-1): min_abs = min(min_abs, abs(arr[i+1]-arr[i])) for i inrange(0, len(arr)-1): if min_abs == abs(arr[i+1]-arr[i]): ans.append((arr[i],arr[i+1])) return ans
1201. Ugly Number III
求出能被 a 或 b 或 c 整除的第 n 个数。
思路:二分
详解:求一个数前面有多少个a的倍数,b的倍数,c的倍数就可以知道这个数是第几个数了,注意要用容斥原理处理ab,
bc, ac 和 abc,在倍数相关处理的过程中要算LCM。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
defgcd(x, y): return x ifnot y else gcd(y, x%y) deflcm(x, y): return x*y//gcd(x, y) classSolution: defnthUglyNumber(self, n: int, a: int, b: int, c: int) -> int: defnumber(n, a, b, c): return n//a+n//b+n//c-n//(lcm(a,b))-n//(lcm(a,c))-n//(lcm(c,b))+n//(lcm(a,lcm(b,c))) l = 1 r = 2 * 10**9 while l < r - 1: mid = (l+r)//2 if number(mid, a, b, c) < n: l = mid + 1 else: r = mid while number(l, a, b, c) < n: l += 1 return l
classSolution: deffind(self, x): if x != self.fa[x]: self.fa[x] = self.find(self.fa[x]) return self.fa[x] defunion(self, x, y): fax = self.find(x) fay = self.find(y) if fax == fay: return if(self.r[fax] < self.r[fay]): self.fa[fax] = fay else: if(self.r[fax] == self.r[fay]): self.r[fax] += 1 self.fa[fay] = fax defsmallestStringWithSwaps(self, s: str, pairs) -> str: self.fa = [i for i inrange(len(s))] self.r = [0for i inrange(len(s))] for x, y in pairs: self.union(x, y) d = collections.defaultdict(str) for i, ch inenumerate(s): fai = self.find(i) d[fai] += ch for (k, v) in d.items(): d[k] = sorted(v) n = collections.Counter() ans = "" for i, ch inenumerate(s): fai = self.find(i) ans += d[fai][n[fai]] n[fai] += 1 return ans
PS: 并查集最好按秩优化,否则可能TLE(别问我怎么知道的)。
1203. Sort Items
by Groups Respecting Dependencies
deftopoSort(graph): in_degrees = dict((u,0) for u in graph) vertex_num = len(in_degrees) for u in graph: for v in graph[u]: in_degrees[v] += 1 Q = [u for u in in_degrees if in_degrees[u] == 0] Seq = [] while Q: u = Q.pop() Seq.append(u) for v in graph[u]: in_degrees[v] -= 1 if in_degrees[v] == 0: Q.append(v) iflen(Seq) == vertex_num: return Seq return"Fail"
classSolution: defsortItems(self, n: int, m: int, group: List[int], beforeItems: List[List[int]]) -> List[int]: groups = [[] for i inrange(m)] for i, g inenumerate(group): # 将无group的item添加到只包含他自己的group,方便最后进行group间的拓扑排序 if g == -1: group[i] = len(groups) groups.append([i]) else: groups[g].append(i) for i, grp inenumerate(groups): graph = {} for u in grp: graph[u] = [] for u in grp: for v in beforeItems[u]: if group[v] == group[u]: graph[v].append(u) # 对每个group进行内部拓扑排序 groups[i] = topoSort(graph) if groups[i] == "Fail": return [] graph = {} for i inrange(len(groups)): graph[i] = [] # 转换item间的before关系为group之间 for u, ll inenumerate(beforeItems): for v in ll: if group[u] != group[v]: graph[group[v]].append(group[u]) # group间的拓扑排序,排的是下标(index) group_idx = topoSort(graph) if group_idx == "Fail": return [] ans = [] # join together for idx in group_idx: ans += groups[idx] return ans