栈和队列

用一个栈实现另一个栈的排序

思路:

  • 两个栈的数据转移。辅助栈 help 始终从原始 stack 中拿到最小的元素存入,如果遇到 help 栈中即将压入的数据大于栈顶元素,则需要将 help 栈中的数据全部倒出到 stack 中,压入新的最大元素,重复此过程。

image.png

生成窗口最大值的数组

思路:

  • 最大堆。申请一个最大堆 pq 维护窗口的元素,且最大元素位于堆顶,不断从 pq 中移除要离开窗口的元素和添加要进入窗口的函数。(Q:但申请辅助结构 pq 的时间复杂度会增加。)
  • 双端队列(书中方式,没看懂)。

image.png

  1. // 最大堆方法
  2. public class MaxWindowsArray {
  3. public static void main(String[] args) {
  4. MaxWindowsArray obj= new MaxWindowsArray();
  5. int[] arr = {4,3,5,4,3,3,6,7};
  6. int w = 3;
  7. // {5,5,5,4,6,7}
  8. int[] res = obj.getMaxWindowsArray(arr, w);
  9. System.out.println(Arrays.toString(res));
  10. }
  11. public int[] getMaxWindowsArray(int[] arr, int w) {
  12. int[] res = new int[arr.length - w + 1];
  13. int idx = 0;
  14. // 大堆
  15. PriorityQueue<Integer> pq = new PriorityQueue<>(new Comparator<Integer>() {
  16. @Override
  17. public int compare(Integer o1, Integer o2) {
  18. return o2 - o1;
  19. }
  20. });
  21. int left = 0, right = 0;
  22. // 生成第一个窗口,并添加到 pq 中
  23. while (right < w) {
  24. pq.add(arr[right++]);
  25. }
  26. res[idx++] = pq.peek();
  27. int removeWindowVal, enterWindowVal;
  28. while (right < arr.length) {
  29. // 记录要进窗口和出窗口的元素
  30. removeWindowVal = arr[left++];
  31. enterWindowVal = arr[right++];
  32. // 更新 pq 堆
  33. pq.remove(removeWindowVal);
  34. pq.add(enterWindowVal);
  35. // 取窗口最大值
  36. res[idx++] = pq.peek();
  37. }
  38. return res;
  39. }
  40. }

单调栈结构

思路:

  • 单调递减栈的性质:入栈元素前面比它小的所有元素中离它最近的元素。(当栈的结构被破坏时需要对栈中已有元素进行处理)

image.png
https://blog.hackerpie.com/posts/algorithms/monotonous-stacks/monotonous-stacks/
image.png

字符串

字符串的统计字符串

image.png

  1. package org.apache.java.codeviewguide.string;
  2. /**
  3. * 给定一个字符串 str,返回 str 的统计字符串。例如,"aaabbadddffc"的统计字符串为"a3b2a1d3f2c1"。
  4. *
  5. * 补充问题:给定一个字符串的统计字符串cstr,再给定一个整数index,返回cstr所代表的原始字符串上的第index个字符。
  6. * 例如,"a 1 b 100"所代表的原始字符串上第0个字符是'a',第50个字符是'b'。
  7. */
  8. public class CountStringAndFind {
  9. public static void main(String[] args) {
  10. CountStringAndFind obj = new CountStringAndFind();
  11. String str = "aaabbadddffc";
  12. String ret = obj.getCountString(str);
  13. System.out.println(str + " 压缩后的结果为:" + ret);
  14. int idx = 5;
  15. char ch = obj.getCharAtIdx(ret, idx);
  16. System.out.println(ret + " 压缩串中第 " + idx + " 位置的字符为:" + ch);
  17. }
  18. /**
  19. * 压缩串
  20. * @param str
  21. * @return
  22. *
  23. * 时间复杂度:O(N)
  24. * 空间复杂度:O(1)
  25. */
  26. public String getCountString(String str) {
  27. char[] chs = str.toCharArray();
  28. int len = chs.length;
  29. int read = 0, write = 0;
  30. int start = 0; // 字符第一次出现的位置
  31. for (read = 0; read < len; read++) {
  32. if (read == len - 1 || chs[read] != chs[read+1]) {
  33. chs[write++] = chs[read];
  34. int nums = read - start + 1;
  35. // 处理nums计数
  36. StringBuilder sb = new StringBuilder();
  37. while (nums > 0) {
  38. sb.append(nums % 10);
  39. nums /= 10;
  40. }
  41. for (int i = sb.length() - 1; i >= 0; i--) {
  42. chs[write++] = sb.charAt(i);
  43. }
  44. // 更新字符第一次出现的位置
  45. start = read + 1;
  46. }
  47. }
  48. StringBuilder ret = new StringBuilder();
  49. for (int i = 0; i < write; i++) {
  50. ret.append(chs[i]);
  51. }
  52. return ret.toString();
  53. }
  54. /**
  55. * 从压缩串中找个第k个位置的字符
  56. * @param str
  57. * @return
  58. *
  59. * 时间复杂度:O(N)
  60. * 空间复杂度:O(1)
  61. */
  62. public char getCharAtIdx(String str, int idx) {
  63. char[] chs = str.toCharArray();
  64. char curChar = '_'; // 记录当前遍历的char
  65. int sum = 0; // 记录当前字符总数
  66. int num = 0; // 记录某个字符总数,比如,a 的 num=102
  67. for (int i = 0; i < chs.length; i++) {
  68. // Character.isLetterOrDigit(ch) 判断一个字符是字母或数字
  69. if (Character.isDigit(chs[i])) {
  70. num = num * 10 + chs[i] - '0';
  71. } else {
  72. if (curChar != chs[i]) { // 当前char更新了,num重置为0
  73. sum += num;
  74. if (sum >= idx) {
  75. return curChar;
  76. }
  77. num = 0; // 关键:遇到新字符,其后续数字计数从0开始
  78. }
  79. curChar = chs[i];
  80. }
  81. }
  82. return sum + num > idx ? curChar : 0;
  83. }
  84. }

在有序但含有空的数组中查找字符串

image.png
思路:

  • 二分查找。关注两种情况,一种是相等的情况如何处理,一种是 strs[mid] 为空的时候如何处理。 ```java package org.apache.java.codeviewguide.string;

/**

  • 在有序但含有空的数组中查找字符串
  • 给定一个字符串数组strs[],在strs中有些位置为null,但在不为null的位置上,
  • 其字符串是按照字典顺序由小到大依次出现的。再给定一个字符串str,请返回str在strs中出现的最左的位置。 *
  • 举例:
  • strs = {null,”a”,null,”a”,null,”b”,null,”c”,null}
  • str = “a’
  • 返回“a”第一次出现的位置:1 */ public class OrderStrsFindStr { public static void main(String[] args) { // System.out.println(“b”.compareTo(“a”)); // 1

    OrderStrsFindStr obj = new OrderStrsFindStr(); String[] strs = {“a”,”a”,null,”a”,null,”b”,null,”c”,null}; String str = “a”; System.out.println(obj.getIndex(strs, str)); }

    public int getIndex(String[] strs, String str) { if (str == null) return -1; int len = strs.length; int left = 0, right = len - 1; int ret = -1; while (left <= right) { int mid = left + (right - left) / 2; if (strs[mid] != null && strs[mid] == str) { // mid值为str

    1. ret = mid;
    2. right = mid - 1;

    } else if (strs[mid] != null) { // strs[mid] != null,并且不等于 str

    1. if (strs[mid].compareTo(str) >= 0) { // 往左走
    2. right = mid - 1;
    3. } else {
    4. left = mid + 1;
    5. }

    } else { // 最复杂的 strs[mid] == null,此时朝那边走呢

    1. // mid随机朝左右走,遇到不为null的字符串再判断更新left还是right
    2. int p = mid;
    3. while (--p >= left && strs[p] == null) ;
    4. if (p >= left && strs[p].compareTo(str) >= 0) {
    5. ret = strs[p].equals(str) ? p : ret; // 处理相等情况
    6. right = mid - 1;
    7. } else {
    8. left = mid + 1;
    9. }

    } } return ret; } } ```

    字符串的路径转换问题

    image.png
    思路:

  • 根据结果先要知道这道题的本意是要从一张图中找到两个节点距离最近的所有路径集合。所以,第一步是要根据题目信息构建一张图,就需要知道每个节点可直达的所有节点;要知道最短路径,第二步就需要知道每个节点到起点的最短距离(通过图的广度优先遍历实现),第三部就是根据图的深度优先遍历,找到起点到终点的所有最短路径。

扩展:

  • 这道题的思想非常广泛,比如地铁网、社交网等,都是找到两个节点的路径,并从中找出最优路径。

代码:

  1. package org.kwang.java;
  2. import java.util.*;
  3. /**
  4. * 定两个字符串,记为start和to,再给定一个字符串列表list,list中一定包含to,list中没有重复字符串。
  5. * 所有的字符串都是小写的。规定start每次只能改变一个字符,最终的目标是彻底变成to,但是每次变成的新字符串必须在list中存在。
  6. * 请返回所有最短的变换路径。
  7. */
  8. public class TwoStrsMinPaths {
  9. public static void main(String[] args) {
  10. TwoStrsMinPaths obj = new TwoStrsMinPaths();
  11. String start = "abc";
  12. String to = "cab";
  13. List<String> lists = new ArrayList<>(Arrays.asList("cab", "acc","cbc","ccc","cac","cbb","aab","abb"));
  14. obj.findMinPaths(start, to, lists);
  15. }
  16. public List<List<String>> findMinPaths(String start, String to, List<String> lists) {
  17. lists.add(start);
  18. // 1.找到每个str改变一个字符可达的所有nexts字符串
  19. Map<String, ArrayList<String>> nexts = getNexts(lists);
  20. System.out.println("============nexts数组===========");
  21. for (Map.Entry<String, ArrayList<String>> entry : nexts.entrySet()) {
  22. System.out.println(entry.getKey() + " : " + entry.getValue());
  23. }
  24. Map<String, Integer> distances = getMinDistances(start, nexts);
  25. System.out.println("============distances最短距离===========");
  26. for (Map.Entry<String, Integer> entry : distances.entrySet()) {
  27. System.out.println(entry.getKey() + " -> " + start + " : " + entry.getValue());
  28. }
  29. List<List<String>> res = new LinkedList<>();
  30. LinkedList<String> pathList = new LinkedList<>();
  31. getAllShortestPaths(start, to, nexts, distances, pathList, res);
  32. System.out.println("============所有最短距离===========");
  33. for (List<String> list : res) {
  34. System.out.println(list);
  35. }
  36. return res;
  37. }
  38. /**
  39. * 找到从start到to的所有最短路径(图的深度优先遍历)
  40. * @param cur
  41. * @param to
  42. * @param nexts
  43. * @param distances
  44. * @param pathList
  45. * @param res
  46. */
  47. private void getAllShortestPaths(String cur, String to, Map<String, ArrayList<String>> nexts,
  48. Map<String, Integer> distances, LinkedList<String> pathList, List<List<String>> res) {
  49. pathList.add(cur);
  50. if (to.equals(cur)) {
  51. res.add(new LinkedList<>(pathList));
  52. }
  53. for (String str : nexts.get(cur)) {
  54. if (distances.get(str) == distances.get(cur) + 1) {
  55. getAllShortestPaths(str, to, nexts, distances, pathList, res);
  56. }
  57. }
  58. pathList.pollLast();
  59. }
  60. /**
  61. * 找到每个str到start节点的最短距离(图的广度优先遍历)
  62. * @param start
  63. * @param nexts
  64. * @return
  65. */
  66. private Map<String, Integer> getMinDistances(String start, Map<String, ArrayList<String>> nexts) {
  67. Map<String, Integer> distances = new HashMap<>();
  68. distances.put(start, 0);
  69. Queue<String> queue = new LinkedList<>();
  70. queue.offer(start);
  71. // 记录访问过的节点
  72. Set<String> set = new HashSet<>();
  73. set.add(start);
  74. while (!queue.isEmpty()) {
  75. String cur = queue.poll();
  76. for (String str : nexts.get(cur)) {
  77. if (!set.contains(str)) {
  78. queue.add(str);
  79. distances.put(str, distances.get(cur) + 1);
  80. set.add(str);
  81. }
  82. }
  83. }
  84. return distances;
  85. }
  86. /**
  87. * 找打每个str可变换的nexts字符串集合
  88. * @param lists
  89. * @return
  90. */
  91. private Map<String, ArrayList<String>> getNexts(List<String> lists) {
  92. Set<String> dict = new HashSet<>(lists);
  93. Map<String, ArrayList<String>> nexts = new HashMap<>();
  94. for (int i = 0; i < lists.size(); i++) {
  95. nexts.put(lists.get(i), getNext(lists.get(i), dict));
  96. }
  97. return nexts;
  98. }
  99. private ArrayList<String> getNext(String word, Set<String> dict) {
  100. ArrayList<String> list = new ArrayList<>();
  101. char[] chs = word.toCharArray();
  102. for (char ch = 'a'; ch < 'z'; ch++) {
  103. for (int i = 0; i < chs.length; i++) {
  104. if (chs[i] != ch) {
  105. char tmp = chs[i];
  106. chs[i] = ch;
  107. if (dict.contains(String.valueOf(chs))) {
  108. list.add(String.valueOf(chs));
  109. }
  110. chs[i] = tmp;
  111. }
  112. }
  113. }
  114. return list;
  115. }
  116. private void test() {
  117. HashSet<String> dict = new HashSet<>();
  118. dict.add("abc");
  119. dict.add("acc");
  120. String word = "abc";
  121. char[] chs = word.toCharArray();
  122. chs[1] = 'c';
  123. System.out.println("chs = " + String.valueOf(chs));
  124. System.out.println(dict.contains(String.valueOf(chs)));
  125. System.out.println(dict.contains(word));
  126. }
  127. }

二叉树中和为指定值的路径问题

思路:

  • 参考“未排序数组和为给定值的最长子数组长度”,树中从根节点出发的每一条路径相当于一个数组,数组 s[i] 的定义就是树中的层级 level 树,左右节点属于同一级 level。确定了解决思路,然后通过树的遍历(先序(yes)/中序/后序)方式遍历树。(树的问题始终都要进行遍历)

扩展:

  • 是否存在和为指定值的路径;
  • 打印和为指定值的所有路径/最长路径;
  • 路径从根节点开始或者可以跨越根节点;

image.png
image.png

二叉树的按层打印和ZigZag打印

思路:
按层打印:

  • BFS两层遍历。常规方式是使用queue两层遍历,外层判断queue是否空,内部while判断queue的层级size元素是否打印完。(因为要打印层号,遍历过程中要记录当前遍历属于哪一层。)
  • BFS一层遍历。用变量 last 记录当前遍历层的最右节点,nLast 表示下一层遍历的最右节点,当遍历的节点 cur == last 时表示一层元素遍历结束,然后 last = nLast 开始下一层遍历。

按ZigZag打印:

  • BFS两层遍历。和层打印思路一类似,无非就是根据每一层规则确定先添加最左还是最右节点,所以这里选择使用双端队列,左到右遍历添加节点到队列尾部,先添加右孩子再添加左孩子,右到左遍历添加节点到队列头部,先添加左孩子再添加右孩子。

image.png

二叉树中某个节点的后继节点

image.png
代码:

  1. /**
  2. * 二叉树中序遍历下某个节点的后继节点
  3. */
  4. public class TreeNextNode {
  5. private static class Node {
  6. int data;
  7. Node left;
  8. Node right;
  9. Node parent;
  10. public Node(int data) {
  11. this.data = data;
  12. }
  13. }
  14. public Node getNextNode(Node node) {
  15. if (node == null)
  16. return null;
  17. if (node.right != null) { // 获取右孩子的最左节点
  18. return mostLeftNode(node.right);
  19. } else {
  20. // 没有右子树,则判断node和parent的关系
  21. // 如果node为parent的left节点,则返回parent节点
  22. Node parent = node.parent;
  23. while (parent != null && node != parent.left) {
  24. node = parent;
  25. parent = node.parent;
  26. }
  27. return parent;
  28. }
  29. }
  30. public Node mostLeftNode(Node node) {
  31. if (node == null)
  32. return null;
  33. while (node.left != null) {
  34. node = node.left;
  35. }
  36. return node;
  37. }
  38. public static void main(String[] args) {
  39. Node node6 = new Node(6), node3 = new Node(3), node9 = new Node(9);
  40. Node node1 = new Node(1), node4 = new Node(4), node8 = new Node(8), node10 = new Node(10);
  41. Node node2 = new Node(2), node5 = new Node(5), node7 = new Node(7);
  42. node6.left = node3; node6.right = node9;
  43. node3.left = node1; node3.right = node4;
  44. node9.left = node8; node9.right = node10;
  45. node1.right = node2;
  46. node4.right = node5;
  47. node8.left = node7;
  48. node3.parent = node6; node9.parent = node6;
  49. node1.parent = node3; node4.parent = node3;
  50. node8.parent = node9; node10.parent = node9;
  51. node2.parent = node1; node5.parent = node4;
  52. node7.parent = node8;
  53. TreeNextNode obj = new TreeNextNode();
  54. Node ret = obj.getNextNode(node10);
  55. System.out.println(ret == null? 0: ret.data);
  56. }
  57. }

二叉树中两个节点的最近公共祖先

image.png
image.png
代码:

  1. package org.kwang.java;
  2. import java.util.ArrayList;
  3. import java.util.HashMap;
  4. import java.util.List;
  5. import java.util.Map;
  6. /**
  7. * 原问题:给定一棵二叉树的头节点head,以及这棵树中的两个节点o1和o2,请返回o1和o2的最近公共祖先节点。
  8. * 进阶问题:如果查询两个节点的最近公共祖先的操作十分频繁,想法让单条查询的查询时间减少。
  9. * (todo)再进阶问题:给定二叉树的头节点head,同时给定所有想要进行的查询。
  10. * 二叉树的节点数量为N,查询条数为M,请在时间复杂度为O(N+M)内返回所有查询的结果。
  11. */
  12. public class TreeFindNearestParent {
  13. public static void main(String[] args) {
  14. TreeFindNearestParent obj = new TreeFindNearestParent();
  15. /**
  16. * 1
  17. * / \
  18. * 2 3
  19. * / \ / \
  20. * 4 5 6 7
  21. * /
  22. * 8
  23. */
  24. TreeNode o1 = new TreeNode(1), o2 = new TreeNode(2), o3 = new TreeNode(4);
  25. TreeNode o4 = new TreeNode(4), o5 = new TreeNode(5), o6 = new TreeNode(6), o7 = new TreeNode(7);
  26. TreeNode o8 = new TreeNode(8);
  27. o1.left = o2; o1.right = o3;
  28. o2.left = o4; o2.right = o5;
  29. o3.left = o6; o3.right = o7;
  30. o7.left = o8;
  31. TreeNode ret = obj.findNearestParent(o1, o4, o5);
  32. System.out.println(ret.val);
  33. System.out.println("=================");
  34. TreeFindNearestParent obj2 = new TreeFindNearestParent(o1);
  35. TreeNode ret2 = obj2.frequentQuery(o1,o4,o8);
  36. System.out.println(ret2 != null ? ret2.val : null);
  37. // 特殊情况:其中一个为根节点
  38. System.out.println(obj2.frequentQuery(o1, o1,o8).val);
  39. // 特殊情况:节点不在树中
  40. TreeNode ret3 = obj2.frequentQuery(o1, o8, new TreeNode(8));
  41. System.out.println( ret3 != null ? ret3.val : null);
  42. }
  43. /**
  44. * 原问题:找到二叉树中两个节点的最近公共祖先
  45. * @param head
  46. * @param node1
  47. * @param node2
  48. * @return
  49. */
  50. public TreeNode findNearestParent(TreeNode head, TreeNode node1, TreeNode node2) {
  51. if (head == null || head == node1 || head == node2) {
  52. return head;
  53. }
  54. TreeNode left = findNearestParent(head.left, node1, node2);
  55. TreeNode right = findNearestParent(head.right, node1, node2);
  56. System.out.println("node = " + head.val + "; left = " + (left != null ? left.val : null) +
  57. "; right = " + (right != null ? right.val : null));
  58. if (left != null && right != null) {
  59. return head;
  60. }
  61. return left != null ? left : right;
  62. }
  63. /**
  64. * 进阶问题:频繁查找二叉树中两个节点的最近公共祖先。
  65. * 思路:
  66. * - 存储每个节点的父亲节点
  67. * - 先向上遍历得到node1的所有父亲节点,然后遍历node2的父亲节点,遇到相同的则返回。
  68. * 扩展:
  69. * - 记录父亲节点可以找到根节点到叶子节点的所有路径
  70. * @param node1
  71. * @param node2
  72. * @return
  73. */
  74. public TreeNode frequentQuery(TreeNode head, TreeNode node1, TreeNode node2) {
  75. if (head == null || head == node1 || head == node2) {
  76. return head;
  77. }
  78. if (!(isTreeNode(head, node1) && isTreeNode(head, node2))) {
  79. return null;
  80. }
  81. List<TreeNode> parentList = new ArrayList<>();
  82. // 统计node1的所有父亲节点
  83. while (parentMap.containsKey(node1)) {
  84. node1 = parentMap.get(node1);
  85. if (node1 != null) parentList.add(node1);
  86. }
  87. while (!parentList.contains(node2)) {
  88. node2 = parentMap.get(node2);
  89. }
  90. return node2;
  91. }
  92. Map<TreeNode, TreeNode> parentMap;
  93. public TreeFindNearestParent() {}
  94. /**
  95. * 初始化map
  96. * @param head
  97. */
  98. public TreeFindNearestParent(TreeNode head) {
  99. parentMap = new HashMap<>();
  100. if (head != null) {
  101. parentMap.put(head, null);
  102. }
  103. setParent(head);
  104. }
  105. private void setParent(TreeNode head) {
  106. if (head == null) {
  107. return;
  108. }
  109. if (head.left != null) {
  110. parentMap.put(head.left, head);
  111. }
  112. if (head.right != null) {
  113. parentMap.put(head.right, head);
  114. }
  115. setParent(head.left);
  116. setParent(head.right);
  117. }
  118. /**
  119. * 判断一个节点是否是树中的节点
  120. * @param head
  121. * @param node
  122. * @return
  123. */
  124. public boolean isTreeNode(TreeNode head, TreeNode node) {
  125. if (head == null) {
  126. return false;
  127. }
  128. if (head == node) {
  129. return true;
  130. }
  131. boolean left = isTreeNode(head.left, node);
  132. boolean right = isTreeNode(head.right, node);
  133. return left == true ? true : right;
  134. }
  135. }

数组和矩阵

未排序正数数组和为指定值的最长子数组长度

思路:

  • 思路一:left 指针从 0 开始,right 也从 0 位置开始作为窗口的右边界,两层遍历,时间复杂度为 O(n^2)。
  • 思路二:sum 为 arr[left, right] 数组区间的和,left 和 right 都从 0 开始,判断 sum 和目标和 k 的大小,来决定 left 还是 right 的移动。如果 sum = k,记录 len,left + 1,

扩展:

  • 和为指定值的所有子数组/最长子数组
  • 数组中数据有负数问题又如何处理?

image.png

未排序数组和为给定值的最长子数组

思路:

  • 用 s[i] 表示 arr[0, i] 的元素和,arr[i, j] 区间的元素和为 s[j] - s[i-1]。如果历史 s[n] 数组中存在 (s[i] - k) 值的位置,说明该区间段有和为 k 的子数组。

例:数组 arr = [10,1,0,-1,2,-2,0,-1,1,2],和 k = 2。

idx s[i] map-key map-value
(s出现的位置)
备注
0 10 10 0
1 11 11 1
2 11

不更新,因为是求最长数组
3 10 10 3
4 12 记录 len
5 10
不更新
6 10 不更新
7 9 9 7
8 10 不更新
9 12
记录 len

image.png