📣 VIP通行证夏日特惠 限时立减$68
楼主: AChris
跳转到指定楼层
上一主题 下一主题
收起左侧

刷题skill+编程cultivation+记录

🔗
 楼主| AChris 2019-2-22 01:07:15 | 只看该作者
全局:
AChris 发表于 2019-2-22 01:05
02/21/2019 Day16

Leetcode 443. String Compression

Integer.toString(count).toCharArray()
这个函数挺有用的,要记住
回复

使用道具 举报

🔗
 楼主| AChris 2019-2-23 03:49:50 | 只看该作者
全局:
02/22/2019 Day17

LeetCode 79. Word Search
【非常好的一题👍】

解题思路:本题算事backtracking / DFS 中比较复杂的一题。还是有一些技巧值得学习。

首先,我们并不清楚word的第一个字母会在board中哪里找到,所以说,第一次branch的话,要从rootbranch到board当中所有的element。
之后的branch,我们就在之前的node的基础上,往上下左右四个方向branch。

其次,往四个方向branch,可能出现一个问题,就是会重复使用之前使用过的字母。那么这里有一个【技巧】,就是利用【‘#’】来替换已经用过的字母,之后recover的时候再复原就好。

第三,base case的就是,我们一直branch,当搜索的depth大于等于word.lenght的时候,也就是我们找到word的时候。

最后,注意不要 index out of bound

以上


  1. class Solution {
  2.     public boolean exist(char[][] board, String word) {
  3.         // board: m*m, word: k
  4.         // time: O(m * n * 4 ^ k) 99.56%
  5.         // space: O(k) 96.62%
  6.         
  7.         // ABCCED
  8.         //                             root
  9.         //                /       / / / \ \ \ \ \           \  (first branch to all elements)
  10.         //              A(0,0)                         A(2, 0)  (rest branch to 4 direction)
  11.         //             /  | | \                        / | | \
  12.         //          B(0,1)
  13.         //          / | | \
  14.         
  15.         if(board == null || board.length == 0 || board[0] == null || board[0].length == 0 || word == null) return false;
  16.         
  17.         for (int i = 0; i < board.length; i++) {
  18.             for (int j = 0; j < board[0].length; j++) {
  19.                 if (exist(board, word, 0, i, j)) {
  20.                     return true;
  21.                 }
  22.             }
  23.         }
  24.         return false;
  25.     }
  26.    
  27.     private boolean exist(char[][] board, String word, int start, int i, int j) {
  28.         if (start >= word.length()) return true;
  29.         if (i < 0 || i >= board.length || j < 0 || j >= board[0].length) return false;
  30.         
  31.         // use '#' to replace the used character to avoid reusing
  32.         if (board[i][j] == word.charAt(start)) {
  33.             char c = board[i][j];
  34.             board[i][j] = '#';
  35.             boolean res = exist(board, word, start + 1, i + 1, j) ||
  36.                 exist(board, word, start + 1, i - 1, j) ||
  37.                 exist(board, word, start + 1, i, j + 1) ||
  38.                 exist(board, word, start + 1, i, j - 1);
  39.             board[i][j] = c;
  40.             return res;
  41.         }
  42.         return false;
  43.     }
  44. }
复制代码
回复

使用道具 举报

🔗
 楼主| AChris 2019-2-23 04:18:16 | 只看该作者
全局:
02/22/2019 Day17

LeetCode 20. Valid Parentheses
Importance【4】

这题再次应证了,easy题目中还是有很多值得一刷的类星体。感觉这题如果之前没见过,还是很难想到用stack来解的。

解题思路:本题主要利用了stack push的数据和pop的数据有一种类似回文的性质。依次根据见到的 ( [ { 并push进他们的另一面。遇到另一面时候,再pop出来看和现在遇到的一不一样。


  1. class Solution {
  2.     public boolean isValid(String s) {
  3.         // time: O(n) 98.12%
  4.         // space: O(n) 30.42%
  5.         
  6.         /*
  7.         Parenthese is some specific kind of problem.
  8.         when we come across this kind of problem, always try to solve it with Stack.
  9.         since:
  10.         123456
  11.         stack:123456
  12.         pop: 654321
  13.         */
  14.         
  15.         /*
  16.         case 1: "()[]{}"
  17.         true
  18.         case 2: "(]"
  19.         fasle
  20.         case 3: "([)]"
  21.         fasle
  22.         */
  23.         
  24.         if (s == null || s.length() == 0) return true;
  25.         Stack<Character> stack = new Stack<> ();
  26.         for (char c : s.toCharArray()) {
  27.             if (c == '(') {
  28.                 stack.push(')');
  29.             } else if (c == '[') {
  30.                 stack.push(']');
  31.             } else if (c == '{') {
  32.                 stack.push('}');
  33.             } else {
  34.                 // we get )/]/} at first or mess the order
  35.                 if (stack.isEmpty() || stack.pop() != c) return false;
  36.             }
  37.         }
  38.         // if stack is empty then every things fine
  39.         return stack.isEmpty();
  40.     }
  41. }
复制代码
回复

使用道具 举报

🔗
 楼主| AChris 2019-2-24 00:16:11 | 只看该作者
全局:

02/22/2019 Day18

LeetCode 70. Climbing Stairs
Importance【4】

解题思路: 这题还是很重要的, 主要是自己第一次见到将问题往dynamic programming中的fibonacci number转化
另外注意,用backtracking也可以,但是因为没有像DP中利用之前计算出来的结果,所以会做很多重复计算,本题中用这个会导致time limit exceed



  1. class Solution {
  2.     // method1:
  3.     public int climbStairs(int n) {
  4.         // time: O(n)
  5.         // space: O(1)
  6.         /*  ==== Fibonacci number ====
  7.             define f(n): n -> how many distinct ways to n
  8.             base case: f(0) = f(1) = 1
  9.             induction f(n) = f(n - 1) + f(n - 2)
  10.         */
  11.         // oneStep denotes f(n-1) since from n-1 to n only need one step
  12.         if (n <= 1) return 1;
  13.         int oneStep = 1, twoStep = 1, res = 0;
  14.         for (int i = 2; i <= n; i++) {
  15.             res = oneStep + twoStep;
  16.             twoStep = oneStep;
  17.             oneStep = res;               
  18.         }
  19.         return res;
  20.     }
  21.    
  22.     // // method2: works but time limit exceeded e.g. n = 45
  23.     // public int climbStairs(int n) {
  24.     //     /*
  25.     //     Some drawback of recursive:
  26.     //     In this recursive tree, we didn't use some common feature. for example, we calculate how many ways there are when n = 3 twice.
  27.     //                    n = 5
  28.     //                  /      \
  29.     //                 4        3
  30.     //              /    \     /  \
  31.     //              3    2     2   1
  32.     //             / \
  33.     //            2   1
  34.     //     */
  35.     //     if (n == 0) return 1;
  36.     //     if (n <= 2) return n;
  37.     //     return climbStairs(n - 1) + climbStairs(n - 2);
  38.     // }
  39. }
复制代码

补充内容 (2019-2-24 00:16):
02/23/2019 Day18
为什么日期总是写错。。。
回复

使用道具 举报

🔗
 楼主| AChris 2019-2-24 10:03:10 | 只看该作者
全局:
02/23/2019 Day18

Leetcode 102. Binary Tree Level Order Traversal
Importance【4】

解题思路:这题如题所讲,是树结构的按层遍历。
主要分为两种方法,一种是BFS的方法,利用一个queue实现,每次循环的时候,把每一层的数从queue拿出来,存到result 里,并将该层的下一层再offer到queue里去。
另一种是DFS,正常递归写法。

解题技巧:
1.利用queue实现BFS


  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. *     int val;
  5. *     TreeNode left;
  6. *     TreeNode right;
  7. *     TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. class Solution {
  11.    
  12.     // method 1: Using BFS by Queue
  13.     public List<List<Integer>> levelOrder(TreeNode root) {
  14.         // time: O(n) 85.87%
  15.         // space: O(n) 32.65%
  16.         
  17.         List<List<Integer>> res = new ArrayList<> ();
  18.         if (root == null) return res;
  19.    
  20.         Queue<TreeNode> queue = new LinkedList<> ();
  21.         queue.add(root);
  22.         while (!queue.isEmpty()) {
  23.             int size = queue.size();
  24.             List<Integer> curLevel = new ArrayList<> ();
  25.             for (int i = 0; i < size; i++) {
  26.                 TreeNode cur = queue.remove();
  27.                 curLevel.add(cur.val);
  28.                 if (cur.left != null) queue.add(cur.left);
  29.                 if (cur.right != null) queue.add(cur.right);
  30.             }
  31.             res.add(curLevel);
  32.         }
  33.         return res;
  34.     }
  35.    
  36. //     // method 2: Using DFS
  37. //     public List<List<Integer>> levelOrder(TreeNode root) {
  38. //         // time: O(n) 100%
  39. //         // space: O(n) 5.51%
  40. //         List<List<Integer>> res = new ArrayList<> ();
  41. //         if (root == null) return res;
  42. //         helper(res, root, 0);
  43. //         return res;
  44. //     }
  45.    
  46. //     private void helper(List<List<Integer>> res, TreeNode cur, int level) {
  47. //         if (cur == null) return;
  48. //         if (level >= res.size()) {
  49. //             res.add(new ArrayList<> ());
  50. //         }
  51. //         res.get(level).add(cur.val);
  52. //         helper(res, cur.left, level + 1);
  53. //         helper(res, cur.right, level + 1);
  54. //         return;
  55. //     }
  56. }
复制代码
回复

使用道具 举报

🔗
 楼主| AChris 2019-2-25 00:18:28 | 只看该作者
全局:
02/24/2019 Day19

Leetcode 114. Flatten Binary Tree to Linked List
Importance【4】

解题思路:
本题是一道类似于traversal的题目,解法使用的递归。
将一个tree flatten分三步:
1.把右面的sub tree flatten
2.把右子树放到最左节点的最右子树上
3.把左子树放到右子树上
       1                        1                   1
     /    \       ->          /        ->          \
   2.     3                 2                        2
                                \                        \
                                 3                       3

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. *     int val;
  5. *     TreeNode left;
  6. *     TreeNode right;
  7. *     TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. class Solution {
  11.    
  12.     private TreeNode prev = null;
  13.         
  14.     public void flatten(TreeNode root) {
  15.         // time: O(n) 100%
  16.         // space: O(1) 5.09%
  17.    
  18.         // similar to the some tree traversal (right -> left -> root)
  19.         if (root == null) return;
  20.         flatten(root.right);
  21.         flatten(root.left);
  22.         root.right = prev;
  23.         root.left = null;
  24.         prev = root;
  25.     }
  26. }
复制代码
回复

使用道具 举报

🔗
 楼主| AChris 2019-2-26 01:05:31 | 只看该作者
全局:

02/25/2019 Day20

Leetcode 104. Maximum Depth of Binary Tree
Importance【3】

解题思路:
非常简单的一道题。主要是利用函数自己本身的递归思路求解。别忘了+1。



  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. *     int val;
  5. *     TreeNode left;
  6. *     TreeNode right;
  7. *     TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. class Solution {
  11.     public int maxDepth(TreeNode root) {
  12.         // time: O(n) 100%
  13.         // space: O(n) 9.61%
  14.         if (root == null) return 0;
  15.         return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
  16.     }
  17. }
复制代码
回复

使用道具 举报

🔗
 楼主| AChris 2019-2-26 02:00:33 | 只看该作者
全局:
02/25/2019 Day20

Leetcode 105. Construct Binary Tree from Preorder and Inorder Traversal
Importance【5】

解题思路:
一道有些难度的题目。
主要是要理解inorder与preorder。
inorder的话是 left -> root -> right,在array中,每一个root的左边是他的左子树,右边是右子树
preorder的话是root -> left -> right,在array中,可以根据size找到root的值

然后,主要利用递归,不断给root的左右子树赋值


  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. *     int val;
  5. *     TreeNode left;
  6. *     TreeNode right;
  7. *     TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. class Solution {
  11.     public TreeNode buildTree(int[] preorder, int[] inorder) {
  12.         // time: O(n^2)
  13.         // space: O(n)
  14.         /*
  15.               3
  16.              / \
  17.             9   20
  18.                /  \
  19.               15   7
  20.             
  21.              preorder = [3, 9, 20, 15, 7]
  22.                 root, left, right
  23.             
  24.              inorder = [9, 3, 15, 20, 7]
  25.                 left, root, right
  26.              for each node, left=side is left children & parents, right-side is right children
  27.         */
  28.         return helper(0, 0, preorder.length - 1, preorder, inorder);
  29.     }
  30.    
  31.     private TreeNode helper(int preStart, int inStart, int inEnd, int[] preorder, int[] inorder) {
  32.         if (preStart > preorder.length - 1 || inStart > inEnd) return null;
  33.         
  34.         TreeNode root = new TreeNode(preorder[preStart]);
  35.         int inIndex = -1;
  36.         
  37.         for (int i = inStart; i < inorder.length; i++) {
  38.             if (root.val == inorder[i]) inIndex = i;
  39.         }
  40.         
  41.         root.left = helper(preStart + 1, inStart, inIndex - 1, preorder, inorder);
  42.         // size of left subtree: inIndex - inStart
  43.         root.right = helper(preStart + inIndex - inStart + 1, inIndex + 1, inEnd, preorder, inorder);
  44.             
  45.         return root;
  46.     }
  47. }
复制代码
回复

使用道具 举报

无效楼层,该帖已经被删除
🔗
 楼主| AChris 2019-2-27 09:32:04 | 只看该作者
全局:
02/25/2019 Day21

Leetcode 101. Symmetric Tree
Importance【4】

解题思路:
挺有意思的一道题,属于那种见过秒做,没见过还挺难想的那种。
关键是利用递归,把值应该相同的两个node一对一对送进helper函数里面,去检验他们的值是否相同。


  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. *     int val;
  5. *     TreeNode left;
  6. *     TreeNode right;
  7. *     TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. class Solution {
  11.     public boolean isSymmetric(TreeNode root) {
  12.         // time: O(n) 100%
  13.         // space: O(logn) 5.12%
  14.         
  15.         if (root == null) return true;
  16.         return helper(root.left, root.right);
  17.     }
  18.    
  19.     private boolean helper(TreeNode left, TreeNode right) {
  20.         if (left == null && right == null) return true;
  21.         if (left == null || right == null) return false;
  22.         
  23.         if (left.val == right.val && helper(left.left, right.right) && helper(left.right, right.left)) return true;
  24.         
  25.         return false;
  26.     }
  27. }
复制代码




补充内容 (2019-2-28 03:36):

日期更正:02/26/2019 Day21
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表