二分法 如果是左右闭区间 则left right
# # This is BinaryMatrix s API interface. # You should not implement it, or speculate about its implementation #class BinaryMatrix(object): # def get(self, row: int, col: int) - int: # def dimensions(self) - list[]: class Solution: def leftMostColumnWithOne(self, binaryMatrix: BinaryMatrix ) - int: rows,cols binaryMatrix.dimensions() mincol [101]*rows for i in range(rows): x,y 0,cols-1 while x y: mid (x y) // 2 condition binaryMatrix.get(i,mid) 1 if mid 0 and condition: mincol[i] mid break elif condition and binaryMatrix.get(i,mid-1) 0: mincol[i] mid break elif condition: y mid - 1 else: x mid 1 return min(mincol) if min(mincol) ! 101 else -1
class Solution: def findBuildings(self, heights: List[int]) - List[int]: n len(heights) maxvalue 0 ans [] for i in range(n-1,-1,-1): if heights[i] maxvalue: ans.append(i) maxvalue heights[i] return ans[::-1]
class Solution: def angleClock(self, hour: int, minutes: int) - float: hour hour % 12 degreehour 360*(hour / 12) (minutes/60) *30 degreemin 360*(minutes / 60) diff1 abs(degreemin-degreehour) diff2 360 - diff1 return min(diff1,diff2)
# 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 rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) - int: ans 0 if not root: return 0 def dfs(node): nonlocal ans if not node: return if node.val low and node.val high: ans node.val dfs(node.left) dfs(node.right) dfs(root) return ans
notice:
sort 列表的时候会按照[0], [1] 的方式来sort 所以用一个lambda只排序第一个
其次 越接近root的点要越前面
# 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 verticalOrder(self, root: Optional[TreeNode]) - List[List[int]]: if not root: return [] dictnode defaultdict(list) start 0 deep 0 def addnode(node,position,deep): if not node: return nonlocal dictnode dictnode[position] [[deep,node.val]] addnode(node.left,position-1,deep 1) addnode(node.right,position 1,deep 1) addnode(root,start,deep) minvalue min(dictnode) maxvalue max(dictnode) ans [] print(dictnode) for i in range(minvalue,maxvalue 1): if dictnode[i]: dictnode[i].sort(key lambda a:a[0]) ans [[node[1] for node in dictnode[i]]] return ans



