剑指 Offer 55. 平衡二叉树
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def afterOrder(self,node): if node==None: return 0,0 else: d1,res1 =self.afterOrder(node.left) d2,res2 = self.afterOrder(node.right) return max(d1+1,d2+1),max(abs(d2-d1),max(res1,res2)) def isBalanced(self, root: TreeNode) -> bool: d,res = self.afterOrder(root) # print(d,res) if res>1: return False else: return True
剑指 Offer 57 - II. 和为s的连续正数序列
class Solution: def findContinuousSequence(self, target: int) -> List[List[int]]: res=[] for i in range(2,target): if i%2==1: if target%i==0 and target//i - i//2>0: start = target//i - i//2 end = start+ i # print(res) res.append([j for j in range(start,end)]) if i%2==0: #print(target%i,i//2,target//i - i//2) if target%i==i//2 and target//i - i//2+1>0: start = target//i - i//2+1 end = target//i + i//2+1 res.append([j for j in range(start,end)]) res.sort() return res
剑指 Offer 45. 把数组排成最小的数
1、转成字符串,对字符串排序:
2、两个字符串前后组成一个数,小的排在前
class Solution: def minNumber(self, nums: List[int]) -> str: for i in range(len(nums)): nums[i] = str(nums[i]) nums.sort() t1='' # print(nums) for i in range(len(nums)-1): for j in range(i+1,len(nums)): if len(nums[i])<len(nums[j]): if nums[i]+nums[j]>nums[j]+nums[i]: t = nums[j] nums[j] = nums[i] nums[i] = t for i in range(len(nums)): t1 += nums[i] #print(nums) return t1