1、杨辉三角2
题目描述:https://leetcode.cn/problems/pascals-triangle-ii/
class Solution:
def getRow(self, rowIndex: int) -> List[int]:
ret = [1]
for i in range(rowIndex):
ret.append(1)
for j in range(1, len(ret) - 1):
if j == 1:
temp = ret[j]
ret[j] = ret[j] + 1
else:
tempHere = ret[j]
ret[j] = ret[j] + temp
temp = tempHere
return ret
2、买股票的最佳时机
题目描述:https://leetcode.cn/problems/best-time-to-buy-and-sell-stock/
class Solution:
def maxProfit(self, prices: List[int]) -> int:
minprice = float('inf')
maxprofit = 0
for price in prices:
minprice = min(minprice, price)
maxprofit = max(maxprofit, price - minprice)
return maxprofit
3、验证回文串
题目描述:https://leetcode.cn/problems/valid-palindrome/
class Solution:
def isPalindrome(self, s: str) -> bool:
s = s.lower()
left, right = 0, len(s) - 1
while left < right:
while left < right and not s[left].isalnum():
left += 1
while left < right and not s[right].isalnum():
right -= 1
if left < right and s[left] != s[right]:
return False
left += 1
right -= 1
return True
4、只出现一次的数字
题目描述:https://leetcode.cn/problems/single-number/
class Solution:
def singleNumber(self, nums: List[int]) -> int:
for x in nums:
count1=nums.count(x)
if count1==1:
return x
5、环形链表
题目描述:https://leetcode.cn/problems/linked-list-cycle/
class Solution:
def hasCycle(self, head: ListNode) -> bool:
if not head or not head.next:
return False
slow = head
fast = head.next
while slow != fast:
if not fast or not fast.next:
return False
slow = slow.next
fast = fast.next.next
return True
6、二叉树的前序遍历
题目描述:https://leetcode.cn/problems/binary-tree-preorder-traversal/
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
res = []
def preorder(root):
if root:
res.append(root.val)
preorder(root.left)
preorder(root.right)
preorder(root)
return res
7、二叉树的后序遍历
题目描述:https://leetcode.cn/problems/binary-tree-postorder-traversal/
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def postorderTraversal(self, root: TreeNode) -> List[int]:
if not root:
return []
stack = [root]
res = []
while stack:
node = stack.pop()
if not node.left and not node.right:
res.append(node.val)
continue
left, right = node.left, node.right
node.left = node.right = None
stack += [ i for i in [node, right, left] if i]
return res