比特位计算
给定一个非负整数 num。对于 0 ≤ i ≤ num 范围中的每个数字 i ,计算其二进制数中的 1 的数目并将它们作为数组返回。
链接:https://leetcode-cn.com/problems/counting-bits/
class Solution:
def countBits(self, num: int) -> List[int]:
a=[]
for i in range(num+1):
a.append(bin(0^i).count('1'))
return a
二叉树的中序遍历
给定一个二叉树的根节点 root ,返回它的 中序 遍历。
链接:https://leetcode-cn.com/problems/binary-tree-inorder-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 inorderTraversal(self, root: TreeNode) -> List[int]:
# a=[]
# def in_order(root):
# if root:
# in_order(root.left)
# a.append(root.val)
# in_order(root.right)
# in_order(root)
# return a
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
if not root:
return []
return self.inorderTraversal(root.left) + [root.val] + self.inorderTraversal(root.right)
旋转图像
给定一个 n × n 的二维矩阵表示一个图像。将图像顺时针旋转 90 度。
说明:你必须在原地旋转图像,这意味着你需要直接修改输入的二维矩阵。请不要使用另一个矩阵来旋转图像。
链接:https://leetcode-cn.com/problems/rotate-image/
# 先上下翻转,再对角翻转
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
for i in range(len(matrix)//2):
matrix[i],matrix[len(matrix)-i-1]=matrix[len(matrix)-i-1],matrix[i]
for i in range(len(matrix)):
for j in range(i):
matrix[i][j],matrix[j][i]=matrix[j][i],matrix[i][j]
组合总数
给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的数字可以无限制重复被选取。
链接:https://leetcode-cn.com/problems/combination-sum
class Solution(object):
def combinationSum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
candidates = sorted(candidates)
ans = []
def find(s, use, remain):
for i in range(s, len(candidates)):
c = candidates[i]
if c == remain:
ans.append(use + [c])
if c < remain:
find(i, use + [c], remain - c)
if c > remain:
return
find(0, [], target)
return ans
根据身高重建队列
假设有打乱顺序的一群人站成一个队列,数组 people 表示队列中一些人的属性(不一定按顺序)。每个 people[i] = [hi, ki] 表示第 i 个人的身高为 hi ,前面 正好 有 ki 个身高大于或等于 hi 的人。
请你重新构造并返回输入数组 people 所表示的队列。返回的队列应该格式化为数组 queue ,其中 queue[j] = [hj, kj] 是队列中第 j 个人的属性(queue[0] 是排在队列前面的人)。
链接:https://leetcode-cn.com/problems/queue-reconstruction-by-height
class Solution:
def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
people.sort(key = lambda x : (x[0], -x[1]))
a = [[] for i in range(len(people))]
for i in people:
h = i[1]
for j in range(len(a)):
if h == 0 and not a[j]:
a[j] = i
break
if not a[j]:
h -= 1
return a