classSolution: defnumPrimeArrangements(self, n: int) -> int: pl = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97] s = sum([i <= n for i in pl]) ans = 1 for i inrange(1, s+1): ans *= i ans %= (10**9+7) for i inrange(1, (n-s)+1): ans *= i ans %= (10**9+7) return ans
1176. Diet Plan Performance
长度为 \(k\) 的连续子区间的和<
lower丢1分,> upper得一分,问最后得分。
简单求和。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution: defdietPlanPerformance(self, calories, k: int, lower: int, upper: int) -> int: cnt = 0 s = 0 ans = 0 for idx, cal inenumerate(calories): s += cal if idx >= k-1: if s > upper: ans += 1 if s < lower: ans -= 1 if idx-k+1 >= 0: s -= calories[idx-k+1] return ans
classSolution: defcanMakePaliQueries(self, s: str, queries: List[List[int]]) -> List[bool]: sto = [[0] * 26for i inrange(len(s)+1)] for idx, ch inenumerate(s, 1): for i inrange(26): sto[idx][i] = 1if ((ord(ch)-ord('a'))==i) else0 sto[idx][i] += sto[idx-1][i] ans = [] for que in queries: l = que[0]+1 r = que[1]+1 k = que[2] tmp = [0] * 27 mi = 0 for i inrange(26): sum_i = sto[r][i]-sto[l-1][i] if (sum_i%2) == 1: mi += 1 ans.append((mi//2) <= k or l>=r) return ans
defword2num(word): res = 0 for ch in word: res |= (1<<(ord(ch)-ord('a'))) return res
classSolution: deffindNumOfValidWords(self, words, puzzles): # ch_dict = [0] * (1<<26) # TLE ch_dict = collections.Counter() for word in words: res = 0 fs = frozenset(word) iflen(fs) <= 7: for ch in word: res |= (1<<(ord(ch)-ord('a'))) ch_dict[res] += 1 ans = [] for puz in puzzles: puz_num = 0 for ch in puz: puz_num |= (1<<(ord(ch)-ord('a'))) res = 0 bit = puz_num whileTrue: ifnot bit: break if (bit >> (ord(puz[0])-ord('a')) & 1 == 1): res += ch_dict[bit] bit = (bit - 1) & puz_num ans.append(res) return ans
小Tip:枚举puzzle状态是位运算枚举puzzle的二进制1,算法如下:
1 2 3 4
bit = mask whileTrue: ifnot bit: break bit = (bit - 1) & mask