摘要: 经典题,黄亮讲过。java版就会难看一点,要写个wrapper class,把结果放在一起。 这里要return三个变量,如果只返回两个变量(node 和 isAncestor),实现起来的逻辑会复杂一些。class Solution { class Result{ TreeNo... 阅读全文
posted @ 2015-02-26 12:47 江南第一少 阅读(188) 评论(0) 推荐(0)
摘要: Assume you know the parent of the node, return the inorder successor. 1 class Solution { 2 public TreeNode inorderSuccessor(TreeNode node) { 3 i... 阅读全文
posted @ 2015-02-26 11:53 江南第一少 阅读(173) 评论(0) 推荐(0)
摘要: 1 public class Solution { 2 public boolean isBalanced(TreeNode root) { 3 int result = checkHeight(root); 4 return result != -1; 5... 阅读全文
posted @ 2015-02-26 09:35 江南第一少 阅读(110) 评论(0) 推荐(0)
摘要: 可以使用一个extra的stack。 1 class Solution { 2 public Stack sortStack(Stack s1) { 3 Stack s2 = new Stack(); 4 while(!s1.isEmpty()) { 5 ... 阅读全文
posted @ 2015-02-26 09:27 江南第一少 阅读(143) 评论(0) 推荐(0)
摘要: 两个stack来实现queue,相似的是两个queue也能实现stack。class Solution { public Stack sortStack(Stack s1) { Stack s2 = new Stack(); while(!s1.isEmpty())... 阅读全文
posted @ 2015-02-24 11:24 江南第一少 阅读(132) 评论(0) 推荐(0)
摘要: check 一个List是不是palindrome, 比如 1 -> 2 -> 3 -> 2 -> 1.迭代版的要么需要reverse整个list,或者需要借助一个stack来存下前半段,而递归版稍微难一点。class Solution { class Result { publ... 阅读全文
posted @ 2015-02-24 11:01 江南第一少 阅读(159) 评论(0) 推荐(0)
摘要: 可以买卖k次,DP来解决,t[i][j] = Math.max(t[i][j - 1], prices[j] + buy) 即得出在prices[j]卖出时的最大利润;buy= Math.max(buy, t[i - 1][j - 1] - prices[j]) 则得出在prices[j]买进后剩下... 阅读全文
posted @ 2015-02-22 22:19 江南第一少 阅读(174) 评论(0) 推荐(0)
摘要: 递归版,因为既要传一个node也要传数字回来,所以只能写个wrapper。class Solution { class IntWrapper { public int value = 0; } public ListNode kthLast(ListNode head, int ... 阅读全文
posted @ 2015-02-19 10:01 江南第一少 阅读(145) 评论(0) 推荐(0)
摘要: Given isSubstring() which checks if one word is a substring of another, write code to check if s2 is a rotation of s1. class Solution { public bool... 阅读全文
posted @ 2015-02-17 06:37 江南第一少 阅读(139) 评论(0) 推荐(0)
摘要: class Solution { public String compress(String str) { int size = countCompression(str); //先check compress之后的size,若更大,返回原string。 if(size >= str.leng... 阅读全文
posted @ 2015-02-17 06:26 江南第一少 阅读(242) 评论(0) 推荐(0)