98. Validate Binary Search Tree
Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
The left subtree of a node contains only nodes with keys less than the node’s key.
The right subtree of a node contains only nodes with keys greater than the node’s key.
Both the left and right subtrees must also be binary search trees.
Example 1:
Input:
2
/ \
1 3
Output: true
Example 2:
5
/ \
1 4
/ \
3 6
Output: false
Explanation: The input is: [5,1,4,null,null,3,6]. The root node’s value
is 5 but its right child’s value is 4.
思路:DFS
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
def valid(r, mmin, mmax):
if r == None:
return True
if r.val <= mmin or r.val >= mmax:
return False
return valid(r.left, mmin, r.val) and valid(r.right, r.val, mmax)
return valid(root, -sys.maxsize, sys.maxsize)
Beat 96.74% python3 2018-05-16
75. Sort Colors
Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
Note: You are not suppose to use the library’s sort function for this problem.
Example:
Input: [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
Follow up:
A rather straight forward solution is a two-pass algorithm using counting sort.
First, iterate the array counting number of 0’s, 1’s, and 2’s, then overwrite array with total number of 0’s, then 1’s and followed by 2’s.
Could you come up with a one-pass algorithm using only constant space?
思路:计数排序
class Solution:
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
count = [0, 0, 0]
for n in nums:
count[n] += 1
index = 0
for i in range(3):
c = count[i]
for j in range(c):
nums[index] = i
index += 1
Beat 100.0% python3 2018-05-16
55. Jump Game
Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Determine if you are able to reach the last index.
Example 1:
Input: [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
Example 2:
Input: [3,2,1,0,4]
Output: false
Explanation: You will always arrive at index 3 no matter what. Its maximum
jump length is 0, which makes it impossible to reach the last index.
思路:维护一个当前可以跳到的最远位置,在这些可到到的位置继续跳,看是否能跳到最后一个位置
class Solution:
def canJump(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
length = len(nums)
if length == 0:
return True
mmax = 0
for i in range(length):
if mmax < i:
return False
if mmax >= length-1:
return True
if i + nums[i] > mmax:
mmax = i+nums[i]
return True
Beat 94.84% python3 2018-05-17
修改if判断顺序:
class Solution:
def canJump(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
length = len(nums)
if length == 0:
return True
mmax = 0
for i in range(length):
if mmax < i:
return False
if i + nums[i] > mmax:
mmax = i+nums[i]
if mmax >= length-1:
return True
return True
Beat 99.09% python3 2018-05-17
但时间并不稳定,多次提交时间不同。
从后往前:
class Solution:
def canJump(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
length = len(nums)
if length <= 1:
return True
last = length - 1
for i in range(length - 1, -1, -1):
if i + nums[i] >= last:
last = i
return last == 0
Beat 99.09% python3 2018-05-17
62. Unique Paths
A robot is located at the top-left corner of a m x n grid (marked ‘Start’ in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked ‘Finish’ in the diagram below).
How many possible unique paths are there?
Above is a 7 x 3 grid. How many possible unique paths are there?
Note: m and n will be at most 100.
Example 1:
Input: m = 3, n = 2
Output: 3
Explanation:
From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
1. Right -> Right -> Down
2. Right -> Down -> Right
3. Down -> Right -> Right
Example 2:
Input: m = 7, n = 3
Output: 28
思路:DP
class Solution:
def uniquePaths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
dp = [1] * n
for i in range(1, m):
for j in range(1, n):
dp[j] += dp[j-1]
return dp[n-1]
Beat 99.02% python3 2018-05-18
思路:排列组合,到目的地要往下走(m-1)次,往右走(n-1)次,即从(m+n-2)选(m-1)
class Solution:
def uniquePaths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
def factorial(x):
ret = 1
for i in range(1, x+1):
ret *= i
return ret
return factorial(m + n - 2) // factorial(n - 1) // factorial(m - 1)
Beat 99.02% python3 2018-05-18
优化求阶乘:
class Solution:
def uniquePaths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
x, y = 1, 1
for i in range(m, m+n-1):
x *= i
for i in range(1, n):
y *= i
return x // y
Beat 100.0% python3 2018-05-18
105. Construct Binary Tree from Preorder and Inorder Traversal
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
For example, given
preorder = [3,9,20,15,7]
inorder = [9,3,15,20,7]
Return the following binary tree:
3
/ \
9 20
/ \
15 7
思路:preorder跟inorder的性质
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def buildTree(self, preorder, inorder):
"""
:type preorder: List[int]
:type inorder: List[int]
:rtype: TreeNode
"""
if len(preorder) == 0 or len(inorder) == 0:
return None
root = TreeNode(preorder[0])
index = inorder.index(preorder[0])
root.left = self.buildTree(preorder[1 : index+1], inorder[0 : index])
root.right = self.buildTree(preorder[index+1 : ], inorder[index+1 : ])
return root
Beat 55.07 % python3 2018-05-20
优化:用字典记录,避免查找根在inorder的位置
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def buildTree(self, preorder, inorder):
"""
:type preorder: List[int]
:type inorder: List[int]
:rtype: TreeNode
"""
def build(start, end):
if start >= end:
return None
root = TreeNode(preorder.pop(0))
index = dict[root.val]
root.left = build(start, index)
root.right = build(index+1, end)
return root
dict = {}
for index, value in enumerate(inorder):
dict[value] = index
return build(0, len(preorder))
Beat 99.24 % python3 2018-05-20