deffindRepeatNumber(nums): fre_dict={} # 使用字典 for i in nums: fre_dict[i] = fre_dict.get(i,0)+1 if fre_dict[i]>1: return i # 另一种思路 ,排序 找nums[i] == nums[i-1]
defsingleNumber(nums): # 1.数学 (sum(set(nums))*3-sum(nums))//2 2.字典思路 3. 位运算 # a^a = 0 a^0 = a 位运算 res = 0 for i in range(32): # 1 <= nums[i] < 2^31限制 idx = 1 << i # 0001 0010 0010 count = 0 for num in nums: if num & idx !=0: count+=1 if count%3 ==1: # 表明唯一的那个数在这一位上为1 res = res|idx return res
defreversePrint(head): res = [] while head: res.append(head.val) head = head.next return res[::-1] # 递归解法 return reversePrint(head.next) + [head.val] if head else []
defhammingWeight(n): # 位运算 n&(n−1) 二进制数字n最右边的 1 变成 0 ,其余不变。 res = 0 while n: res += 1 n &= n - 1 return res # n&1 =1 => n 二进制 最右一位 为 1 ;n&1 = 0 => n 二进制 最右一位 为 0 res = 0 while n: res += n&1 n = n>>1 return res
deffindContinuousSequence(target): # 滑动窗口解决 nums = list(range(1,(target//2+2))) # 候选的最大值不会超高target/2 +1 res = [] start_window,total = 0,nums[0] for end_window in range(1,len(nums)): total += nums[end_window] while total>=target: if total == target: # 窗口和 = target =>当前窗口加入结果 窗口起点右移 res.append(nums[start_window:end_window+1]) total -= nums[start_window] start_window+=1 return res
deflevelOrder(root): from collections import deque ifnot root:return [] queue = deque() queue.append(root) res = [] while queue: level_size = len(queue) for _ in range(level_size): node = queue.popleft() if node.left: queue.append(node.left) if node.right: queue.append(node.right) res.append(node.val) return res
defnthUglyNumber(n): # 带条件的动态规划 dp, a, b, c = [1] * n, 0, 0, 0 for i in range(1, n): n2, n3, n5 = dp[a] * 2, dp[b] * 3, dp[c] * 5 dp[i] = min(n2, n3, n5) if dp[i] == n2: a += 1 if dp[i] == n3: b += 1 if dp[i] == n5: c += 1 return dp[-1]
for i in str[1:]: if'0'<=i<='9': res = res*10 + ord(i) - ord('0') else: break if sign> 0: return res if res < 2**31-1else2**31-1 else: return res*sign if res*sign > -2**31else-2**31
defmyPow(self, x: float, n: int) -> float: ### 分治思想 if n == 0: return1# base if n<0 : x,n = 1/x,-n if n %2 == 0: return self.myPow(x,n//2)**2 else: return x * self.myPow(x,n//2)**2