Leetcode 414 Third Maximum Number
Description:
Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in O(n).
Methods:
We can use an auxiliary array to maintain the top3 value.
And go through the nums to get the top 3.
PS the aux array need to use LONG data type ,otherwise it would cause overflow.
Code:
|
|
Leetcode 236 Lowest Common Ancestor of a Binary Tree
Description:
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”
|
|
For example, the lowest common ancestor (LCA) of nodes 5
and 1
is 3
. Another example is LCA of nodes 5
and 4
is 5
, since a node can be a descendant of itself according to the LCA definition.
Methods:
This problem needs to use recurrence to solve. I still feel very anxious about recurrence. (Need to draw the picture to get the idea).
The method is very simple:
- If p and q are in two different sides of root, root should be the LCA.
- If p and q are in the same side of root, then the LCA would be in that side(recurrence)
Then how to design the recurrence??? How to write from scratch..
|
|
把它当一个黑盒子。从最通用的情况来考虑。
Leetcode 139 Word Break
Description:
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. You may assume the dictionary does not contain duplicate words.
For example, given
s = "leetcode"
,
dict = ["leet", "code"]
.
Return true because "leetcode"
can be segmented as "leet code"
.
Methods:
Dynamic Programming again.LOL
p[i] stands for that whether there is a word break in substring of s[0:i].
So p[i]=true or not(p[j]+s[j:i]) j from 0 to i
Code:
|
|