一、Single Number
给定一个整数的数组,每个数字出现两次,但有一个数字只出现了一次,找到这个单独的数字。
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return reduce(operator.xor,nums)
异或满足交换律,a^a=0 , 0^b=b , 将数组中所有数字全部做异或运算,最后留下的就是单独的数字。
[1,3,2,1,2] => 1^3^2^1^2 => 1^1^2^2^3 =>0^0^3 => 3
二、Maximum Depth of Binary Tree
给定一个二叉树,找到最大树深。
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
### DFS 深度优先遍历
if not root: return 0
return 1+max(self.maxDepth(root.left),self.maxDepth(root.right))
##BFS 广度优先遍历
if not root: return 0
currentLevel=[root]
ctn=0
while currentLevel:
ctn+=1
nextLevel=[]
for i in currentLevel:
if i.left:
nextLevel.append(i.left)
if i.right:
nextLevel.append(i.right)
currentLevel=nextLevel
return ctn
三、 Minimum Depth of Binary Tree
给定一个二叉树,找到最小树深。
class Solution(object):
def minDepth(self, root):
if not root:
return 0
q=[root]
cnt=0
while q:
cnt+=1
tmp=[]
for i in q:
if not i.left and not i.right:
return cnt
if i.left:
tmp.append(i.left)
if i.right:
tmp.append(i.right)
q=tmp
return cnt
#深度,递归,如果左子树为空,那么最小树深是右子树的最小树深
if not root:
return 0
if not root.left:
return 1+self.minDepth(root.right)
if not root.right:
return 1+self.minDepth(root.left)
return 1+min(self.minDepth(root.right),self.minDepth(root.left))
深度优先,简洁的写法
def minDepth(self, root):
if not root: return 0
d = map(self.minDepth, (root.left, root.right))
return 1 + (min(d) or max(d))
def minDepth(self, root):
if not root: return 0
d, D = sorted(map(self.minDepth, (root.left, root.right)))
return 1 + (d or D)