1、2的幂
题目描述:https://leetcode.cn/problems/power-of-two/
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
return n > 0 and n & (n - 1) == 0
2、用栈实现队列
题目描述:https://leetcode.cn/problems/implement-queue-using-stacks/
class MyQueue(object):
def __init__(self):
self.stack1 = []
self.stack2 = []
def push(self, x):
self.stack1.append(x)
def pop(self):
if not self.stack2:
while self.stack1:
self.stack2.append(self.stack1.pop())
return self.stack2.pop()
def peek(self):
if not self.stack2:
while self.stack1:
self.stack2.append(self.stack1.pop())
return self.stack2[-1]
def empty(self):
return not self.stack1 and not self.stack2
3、回文链表
题目描述:https://leetcode.cn/problems/palindrome-linked-list/
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
vals = []
current_node = head
while current_node is not None:
vals.append(current_node.val)
current_node = current_node.next
return vals == vals[::-1]
4、有效的字母异位词
题目描述:https://leetcode.cn/problems/valid-anagram/
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
dict1 = {}
for i in s:
if i not in dict1:
dict1[i] = 1
else:
dict1[i] += 1
dict2 = {}
for i in t:
if i not in dict2:
dict2[i] = 1
else:
dict2[i] += 1
return operator.eq(dict1, dict2)
5、二叉树的所有路径
题目描述:https://leetcode.cn/problems/binary-tree-paths/
class Solution:
def binaryTreePaths(self, root: TreeNode) -> List[str]:
if root is None: return []
result = []
subset = [str(root.val)]
def DFS(root, subset, result):
if root.left is None and root.right is None:
result.append(''.join(subset))
return
if root.left is not None:
subset.append('->' + str(root.left.val))
DFS(root.left, subset, result)
subset.pop()
if root.right is not None:
subset.append('->' + str(root.right.val))
DFS(root.right, subset, result)
subset.pop()
DFS(root, subset, result)
return result
6、各位相加
题目描述:https://leetcode.cn/problems/add-digits/
class Solution:
def addDigits(self, num: int) -> int:
return (num-1) % 9 + 1 if num else 0
7、丑数
题目描述:https://leetcode.cn/problems/ugly-number/
class Solution(object):
def isUgly(self, n):
if n <= 0:
return False
while n % 2 == 0:
n //= 2
while n % 3 == 0:
n //= 3
while n % 5 == 0:
n //= 5
return n == 1