classSolution: defcircularArrayLoop(self, nums: List[int]) -> bool: n = len(nums) Base = 10000 for i inrange(n): if nums[i] >= Base: continue k = i S = Base + i last = -1 t = nums[k] > 0 while (t ^ (nums[k] > 0)) == 0and nums[k] < Base: p = (nums[k] + k) % n last = nums[k] nums[k] = S k = p if k == i: break if (last % n) and nums[k] == S: returnTrue returnFalse
输入:6 输出:3 解释:神奇字符串 S 的前 6 个元素是 “12211”,它包含三个 1,因此返回 3。
python code
1 2 3 4 5 6 7 8 9 10 11 12 13 14
classSolution: defmagicalString(self, n: int) -> int: s = "122" res = 0 k = 1 for i inrange(2, n): m = int(s[i]) for j inrange(m): s += str(k) k = 3 - k for i inrange(n): if s[i] == '1': res += 1 return res
classSolution: deffindRestaurant(self, list1: List[str], list2: List[str]) -> List[str]: l1 = {list1[i]:i for i inrange(len(list1))} l2 = {list2[i]:i for i inrange(len(list2))} inter = set(list1) & set(list2) index = {i:l1[i]+l2[i] for i in inter} res = [] for i in index: if index[i] == min(index.values()): res.append(i) return res