Monotone Stack

今天我们的题目会围绕一种数据结构(单调栈)和相应的解题方法来讲解。总共3道由易到难的题目。 Question Leetcode 739: Daily Temperatures Given a list of daily temperatures T, return a list such that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead. Example given the list of temperatures T = [73, 74, 75, 71, 69, 72, 76, 73], your output should be [1, 1, 4, 2, 1, 1, 0, 0].

Maximum Difference Between Node and Ancestor

Question Leetcode 1026: Given the root of a binary tree, find the maximum value V for which there exists different nodes A and B where V = |A.val - B.val| and A is an ancestor of B. (A node A is an ancestor of B if either: any child of A is equal to B, or any child of A is an ancestor of B.) class TreeNode: def __init__(self, x): self.

Longest Increasing Subsequence (Chinese)

Question This question is from Leetcode 300 Given an unsorted array of integers, find the length of longest increasing subsequence. Examples Input: [10,9,2,5,3,7,101,18] Output: 4 Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4. Note There may be more than one LIS combination, it is only necessary for you to return the length. Your algorithm should run in \( O(N^2) \) complexity. Method 1 Analysis 可以使用Brute force的方法来解决这个问题。 具体来说我们需要试一下所有可能的组合:对于每一个数x,他本身加上他后面的任意一个比他大的数y都可以组成一个increasing subsequence。如果我们已经知道了以y开头(对,就是recursion的思想),最长能组成的subsequence的长度,我们就知道了以x和y开头的最长的长度。但是选y只是以x开头的increasing subsequence的可能性之一。或许有一个数字z也符合条件(比x大,在x的后面),如果以z开头的increasing subsequence 的最长长度比以y开头的长,那么对于x来说,更好地选项就是接上z,以xz开头。 所以,为了知道最长的到底是那个,需要把后面所有符合条件的数都拿来试一下,然后选那个最长的。 时间复杂度是\( O(N!

Inorder Predecessor

Question Given a node in a binary tree, return the inorder predecessor of that node. If it doesn’t exist, return null. Both input and output should be node objects. Node is given as an object with pointers to it’s left child, right child and parent. Examples Example 1 A / \ B C / \ D E / F In order traversal: DBFEAC If give A, then return should be E.

Minimum Point to Traverse Graph

Question There is a directed graph and you can traverse the nodes in this graph by following the directed edges. You can start from any node in this graph and you can pick nodes as start points as many as you needed. What is the minimum number of nodes as start points you need to traverse all the nodes? You will be given a number n as number of vertices in the graph, and a list contains all the edges in the graph.