[
  {
    "path": ".gitignore",
    "content": "# Compiled class file\n*.class\n\n# Log file\n*.log\n\n# BlueJ files\n*.ctxt\n\n# Mobile Tools for Java (J2ME)\n.mtj.tmp/\n\n# Package Files #\n*.jar\n*.war\n*.nar\n*.ear\n*.zip\n*.tar.gz\n*.rar\n\n# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml\nhs_err_pid*\n\n# idea\n*.idea\n*.iml\n\ntarget/\n*.mvn\n*db\n\n# others\n*.extract\n.DS_Store\n"
  },
  {
    "path": "README.md",
    "content": "# [算法练级计划](https://mp.weixin.qq.com/s/6vuaECCmrxrchr5Hc11S5w)\n\n> **既然终要承受痛苦，那么尝试思考的痛总归比承受学习的苦更有意义。**\n\n在正式开始之前，邀请你阅读「[The Key To Accelerating Your Coding Skills](http://blog.thefirehoseproject.com/posts/learn-to-code-and-be-self-reliant/)」，这篇文章将会告诉你如何快速有效地提高自己的编程能力。\n\n## Introduction\n\n**算法练级计划**以面试算法题目为线索，总结归纳面试涉及的算法知识点，整理LeetCode以及「剑指offer」出现的面试题目，在大量的LeetCode题目中梳理一个刷题脉络，让大家能够在有限的时间内，通过面试算法题目的练习，提高算法能力，更加有效地准备面试~\n\n\n* 了解算法练级计划：[算法练级计划](https://mp.weixin.qq.com/s/6vuaECCmrxrchr5Hc11S5w)\n\n* 在开启算法练级计划之前，需要同学们了解至少一门编程语言，我在这里推荐Java语言，Java学习参见：[Java练级攻略](https://mp.weixin.qq.com/s/i-j27vWXPS4kGmxO7i9p9w)，Java学习资源参见：[Java练级资源包](https://mp.weixin.qq.com/s/BomvPTaoAV1rDI6X8yDs-w)\n\n* 准备校招面试时，参见校招攻略：[2019秋招经验谈](https://mp.weixin.qq.com/s/iVHSbojhMSIL37K-UbM41A)\n\n## *1*、 Data Structure and Algorithms\n\n### 目录\n[Data Structure and Algorithms](https://github.com/guokaide/algorithm/blob/master/summary/algorithm.md) \n  \n**数据结构与算法的要点总结**，包括数组、链表、栈、队列、二分查找、排序...不断更新中（每周至少更新一个知识点）...\n\n### 正文\n\n* [数组](https://github.com/guokaide/algorithm/blob/master/summary/algorithm.md#%E6%95%B0%E7%BB%84)\n\n* [链表](https://github.com/guokaide/algorithm/blob/master/summary/algorithm.md#%E9%93%BE%E8%A1%A8)\n\n* [栈](https://github.com/guokaide/algorithm/blob/master/summary/algorithm.md#%E6%A0%88)\n\n* [队列](https://github.com/guokaide/algorithm/blob/master/summary/algorithm.md#%E9%98%9F%E5%88%97)\n\n* [二分查找算法](https://github.com/guokaide/algorithm/blob/master/summary/algorithm.md#%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BE)\n\n* [排序算法](https://github.com/guokaide/algorithm/blob/master/summary/algorithm.md#%E6%8E%92%E5%BA%8F)\n\n* [设计思想](https://github.com/guokaide/algorithm/blob/master/summary/algorithm.md#%E8%AE%BE%E8%AE%A1%E6%80%9D%E6%83%B3)\n\n* [缓存](https://github.com/guokaide/algorithm/blob/master/summary/algorithm.md#%E7%BC%93%E5%AD%98)\n\n## *2*、 Questions\n\n### 目录\n  \n  [Questions](https://github.com/guokaide/algorithm/blob/master/questions/questions.md)\n  \n  > **Talk is cheap, show me the code.**\n\n  算法练级计划核心部分，通过coding，提高代码能力，掌握数据结构与算法。\n  \n  所有问题均选自与校招面试真题，包括问答题，算法题，手撕代码题等。\n  \n  大家可以点击更新列表中的**Title**列的题目，开始算法练级挑战，加油~\n  \n  *ps.不断更新中（每周至少更新3个问题）*...\n  \n### 正文\n\n#### [数组](https://github.com/guokaide/algorithm/blob/master/questions/questions.md#%E6%95%B0%E7%BB%84)\n\n|#|Title|Finished|\n|:---:|:---|:---|\n|001|[数组与泛型动态数组](https://github.com/guokaide/algorithm/blob/master/questions/questions.md#1-%E6%95%B0%E7%BB%84%E4%B8%8E%E6%B3%9B%E5%9E%8B%E5%8A%A8%E6%80%81%E6%95%B0%E7%BB%84)|Yes|\n|002|[1000万整数中查找某个数](https://github.com/guokaide/algorithm/blob/master/questions/questions.md#2-1000%E4%B8%87%E6%95%B4%E6%95%B0%E4%B8%AD%E6%9F%A5%E6%89%BE%E6%9F%90%E4%B8%AA%E6%95%B0)|Yes|\n|003|[约瑟夫问题](https://github.com/guokaide/algorithm/blob/master/questions/questions.md#3-%E7%BA%A6%E7%91%9F%E5%A4%AB%E9%97%AE%E9%A2%98)|Yes|\n\n#### [链表](https://github.com/guokaide/algorithm/blob/master/questions/questions.md#%E9%93%BE%E8%A1%A8)\n\n|#|Title|Finished|\n|:---:|:---|:---|\n|001|[链表与数组](https://github.com/guokaide/algorithm/blob/master/questions/questions.md#1-%E9%93%BE%E8%A1%A8%E4%B8%8E%E6%95%B0%E7%BB%84)|Yes|\n|002|[Reverse Linked List](https://github.com/guokaide/algorithm/blob/master/questions/questions.md#2-reverse-linked-list)|Yes|\n|003|[Middle of the Linked List](https://github.com/guokaide/algorithm/blob/master/questions/questions.md#3-middle-of-the-linked-list)|Yes|\n|004|[LRU Cache](https://github.com/guokaide/algorithm/blob/master/questions/questions.md#4-lru-cache)|Yes|\n|005|[Palindrome Linked List](https://github.com/guokaide/algorithm/blob/master/questions/questions.md#5-palindrome-linked-list)|Yes|\n|006|[Linked List Cycle](https://github.com/guokaide/algorithm/blob/master/questions/questions.md#6-linked-list-cycle)|Yes|\n|007|[Merge Two Sorted Lists](https://github.com/guokaide/algorithm/blob/master/questions/questions.md#7-merge-two-sorted-lists)|Yes|\n|008|[Remove Nth Node From End of List](https://github.com/guokaide/algorithm/blob/master/questions/questions.md#8-remove-nth-node-from-end-of-list)|Yes|\n\n#### [栈](https://github.com/guokaide/algorithm/blob/master/questions/questions.md#%E6%A0%88)\n\n|#|Title|Finished|\n|:---:|:---|:---|\n|001|[Implement Stack using Array](https://github.com/guokaide/algorithm/blob/master/questions/questions.md#1-implement-stack-using-array)|Yes|\n|002|[Implement Stack using Linked List](https://github.com/guokaide/algorithm/blob/master/questions/questions.md#2-implement-stack-using-linked-list)|Yes|\n|003|[Implement Stack using Queues](https://github.com/guokaide/algorithm/blob/master/questions/questions.md#3-implement-stack-using-queues)|No|\n|004|[Implement Queue using Stacks](https://github.com/guokaide/algorithm/blob/master/questions/questions.md#4-implement-queue-using-stacks)|No|\n|005|[Valid Parentheses](https://github.com/guokaide/algorithm/blob/master/questions/questions.md#5-valid-parentheses)|No|\n|006|[Min Stack](https://github.com/guokaide/algorithm/blob/master/questions/questions.md#6-min-stack)|No|\n|007|[Implement the Forward and Backward Functions of the Browser](https://github.com/guokaide/algorithm/blob/master/questions/questions.md#7-implement-the-forward-and-backward-functions-of-the-browser)|No|\n\n#### [队列](https://github.com/guokaide/algorithm/blob/master/questions/questions.md#%E9%98%9F%E5%88%97)\n\n|#|Title|Finished|\n|:---:|:---|:---|\n|001|[Implement Queue using Array](https://github.com/guokaide/algorithm/blob/master/questions/questions.md#1-implement-queue-using-array)|Yes|\n|002|[Implement Queue using Linked List](https://github.com/guokaide/algorithm/blob/master/questions/questions.md#2-implement-queue-using-linked-list)|Yes|\n|003|[Design Circular Queue](https://github.com/guokaide/algorithm/blob/master/questions/questions.md#3-design-circular-queue)|No|\n|004|[Design Circular Deque](https://github.com/guokaide/algorithm/blob/master/questions/questions.md#4-design-circular-deque)|No|\n\n\n#### [二分查找算法](https://github.com/guokaide/algorithm/blob/master/questions/questions.md#%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BE%E7%AE%97%E6%B3%95)\n\n|#|Title|Finished|\n|:---:|:---|:---|\n|001|[二分查找算法](https://github.com/guokaide/algorithm/blob/master/questions/questions.md#1-%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BE%E7%AE%97%E6%B3%95)|Yes|\n|002|[二分查找算法变形问题](https://github.com/guokaide/algorithm/blob/master/questions/questions.md#2-%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BE%E7%AE%97%E6%B3%95%E5%8F%98%E5%BD%A2%E9%97%AE%E9%A2%98)|Yes|\n|003|[旋转数组中的最小值](https://github.com/guokaide/algorithm/blob/master/questions/questions.md#3-%E6%97%8B%E8%BD%AC%E6%95%B0%E7%BB%84%E4%B8%AD%E7%9A%84%E6%9C%80%E5%B0%8F%E5%80%BC)|Yes|\n|004|[Sqrt(x)](https://github.com/guokaide/algorithm/blob/master/questions/questions.md#4-sqrtx)|No|\n\n#### [递归](https://github.com/guokaide/algorithm/blob/master/questions/questions.md#%E9%80%92%E5%BD%92)\n|#|Title|Finished|\n|:---:|:---|:---|\n|001|[Pow(x, n)](https://github.com/guokaide/algorithm/blob/master/questions/questions.md#1-powx-n)|No|\n\n## *3*、 leetcode\n|#|Title|Difficulty|Solution|\n|:---:|:---|:---|:---|\n|876|[Middle of the Linked List](https://leetcode.com/problems/middle-of-the-linked-list/)|Easy|[Java](https://github.com/guokaide/algorithm/tree/master/leetcode/src/middleofthelinkedlist_876)|\n|234|[Palindrome Linked List](https://leetcode.com/problems/palindrome-linked-list/)|Easy|[Java](https://github.com/guokaide/algorithm/tree/master/leetcode/src/palindromelinkedlist_234)|\n|206|[Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/)|Easy|[Java](https://github.com/guokaide/algorithm/tree/master/leetcode/src/reverselinkedlist_206)|\n|146|[LRU Cache](https://leetcode.com/problems/lru-cache/description/) |Hard|[Java](https://github.com/guokaide/algorithm/tree/master/leetcode/src/lrucache_146)|\n|141|[Linked List Cycle](https://leetcode.com/problems/linked-list-cycle/)|Easy|[Java](https://github.com/guokaide/algorithm/tree/master/leetcode/src/linkedlistcycle_141)|\n|021|[Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/)|Easy|[Java](https://github.com/guokaide/algorithm/tree/master/leetcode/src/mergetwosortedlist_21)|\n|019|[Remove Nth Node From End of List](https://leetcode.com/problems/remove-nth-node-from-end-of-list/)|Medium|[Java](https://github.com/guokaide/algorithm/tree/master/leetcode/src/removenthnodefromendoflist_19)|\n\n\n## *4*、 剑指offer\n\n* [「剑指offer题解」（Java版）](https://github.com/guokaide/algorithm/blob/master/solutions/%E5%89%91%E6%8C%87offer%20%E9%A2%98%E8%A7%A3.md)\n\n  「剑指offer」的Java版本题解，不断更新中...\n\n* 更新列表\n\n|#|Title|Solution|\n|:---:|:---|:---|\n|002|[实现单例模式](https://github.com/guokaide/algorithm/blob/master/solutions/%E5%89%91%E6%8C%87offer%20%E9%A2%98%E8%A7%A3.md#2-%E5%AE%9E%E7%8E%B0%E5%8D%95%E4%BE%8B%E6%A8%A1%E5%BC%8F)|[Java](https://github.com/guokaide/algorithm/tree/master/offer/src/com/ex/singleton)|\n|003|[数组中重复的数字](https://github.com/guokaide/algorithm/blob/master/solutions/%E5%89%91%E6%8C%87offer%20%E9%A2%98%E8%A7%A3.md#3-%E6%95%B0%E7%BB%84%E4%B8%AD%E9%87%8D%E5%A4%8D%E7%9A%84%E6%95%B0%E5%AD%97)|[Java](https://github.com/guokaide/algorithm/blob/master/offer/src/com/ex/offer/Ex_03_FindDuplicatedNumInArray.java)|\n\n## Appendix\n#### 1. 如何进行代码测试？\n\n* [题目：二分查找算法](https://github.com/guokaide/algorithm/blob/master/questions/questions.md#1-%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BE%E7%AE%97%E6%B3%95)\n\n* [测试：二分查找算法测试示例](https://github.com/guokaide/algorithm/blob/master/algorithms/src/array/BinarySearchTest.java)\n\n#### 2.刷题笔记\n\n* [戳我](../master/appendix/刷题笔记.md)\n \n## 欢迎大家关注我的公众号： 【算法修炼笔记】\n\n主要分享校招笔试面试经验、数据结构与算法、计算机网络、操作系统、数据库以及法律知识等，完成从码农到工程师的进阶之路~\n\n![algo](https://github.com/guokaide/algorithm/blob/master/pictures/algo.jpg)\n\n"
  },
  {
    "path": "algorithms/src/array/BinarySearch.java",
    "content": "package array;\n\npublic class BinarySearch {\n    // 最简单的二分查找算法：针对有序无重复元素数组\n    // 迭代\n    public static int binarySearch(int[] array, int target) {\n        if (array == null) return -1;\n\n        int lo = 0;\n        int hi = array.length-1; // 始终在[lo, hi]范围内查找target\n\n        while (lo <= hi) {\n            int mid = lo + ((hi - lo) >> 1); // 这里若是 (lo + hi) / 2 有可能造成整型溢出\n\n            if (array[mid] >  target) {\n                hi = mid - 1;\n            } else if (array[mid] < target) {\n                lo = mid + 1;\n            } else {\n                return mid;\n            }\n        }\n\n        return -1;\n    }\n\n    // 递归\n    public static int binarySearchRecur(int[] array, int target) {\n        if (array == null) return -1;\n        return bs(array, target, 0, array.length-1);\n    }\n\n    private static int bs(int[] array, int target, int lo, int hi) {\n        if (lo <= hi) {\n            int mid = lo + ((hi - lo) >> 1);\n            if (array[mid] > target) {\n                return bs(array, target, lo, mid-1);\n            } else if (array[mid] < target) {\n                return bs(array, target, mid+1, hi);\n            } else {\n                return mid;\n            }\n        }\n\n        return -1;\n    }\n\n    // 二分查找变形问题\n    // 1. 查找第一个值等于给定值的元素\n    public static int bsFirst(int[] array, int target) {\n        int lo = 0;\n        int hi = array.length - 1;\n\n        while (lo <= hi) {\n            int mid = lo + ((hi - lo) >> 1);\n\n            if (array[mid] > target) {\n                hi = mid - 1;\n            } else if (array[mid] < target) {\n                lo = mid + 1;\n            } else {\n                if (mid == lo || array[mid-1] != array[mid]) {\n                    return mid;\n                } else {\n                    hi = mid - 1;\n                }\n            }\n        }\n\n        return -1;\n    }\n\n    // 2. 查找最后一个值等于给定值的元素\n    public static int bsLast(int[] array, int target) {\n        int lo = 0;\n        int hi = array.length - 1;\n\n        while (lo <= hi) {\n            int mid = lo + ((hi - lo) >> 1);\n\n            if (array[mid] > target) {\n                hi = mid - 1;\n            } else if (array[mid] < target) {\n                lo = mid + 1;\n            } else {\n                if (mid == hi || array[mid] != array[mid+1]) {\n                    return mid;\n                } else {\n                    lo = mid + 1;\n                }\n            }\n        }\n\n        return -1;\n    }\n\n    // 3. 查找第一个大于等于给定值的元素\n    public static int bsFistGE(int[] array, int target) {\n        int lo = 0;\n        int hi = array.length - 1;\n\n        while (lo <= hi) {\n            int mid = lo + ((hi - lo) >> 1);\n\n            if (array[mid] >= target) {\n                if (mid == 0 || array[mid-1] < target) {\n                    return mid;\n                } else {\n                    hi = mid - 1;\n                }\n            } else {\n                lo = mid + 1;\n            }\n        }\n\n        return -1;\n    }\n\n    // 4. 查找最后一个小于等于给定值的元素\n    public static int bsLastLE(int[] array, int target) {\n        int lo = 0;\n        int hi = array.length - 1;\n\n        while (lo <= hi) {\n            int mid = lo + ((hi - lo) >> 1);\n\n            if (array[mid] <= target) {\n                if (mid == hi || array[mid+1] > target) {\n                    return mid;\n                } else {\n                    lo = mid + 1;\n                }\n            } else {\n                hi = mid - 1;\n            }\n        }\n\n        return -1;\n    }\n}\n"
  },
  {
    "path": "algorithms/src/array/BinarySearchTest.java",
    "content": "package array;\n\nimport org.junit.Assert;\nimport org.junit.Test;\n\npublic class BinarySearchTest {\n\n    // 测试示例（完备）\n    @Test\n    public void testBinarySearch() {\n        int notFound = -1;\n        int target = 6;\n\n        // 测试数组为null\n        int[] arr = null;\n        Assert.assertEquals(notFound, BinarySearch.binarySearch(arr, target));\n\n        // 测试数组为空\n        int[] arr1 = new int[0];\n        Assert.assertEquals(notFound, BinarySearch.binarySearch(arr1, target));\n\n        // 功能测试\n        int[] arr2 = new int[] {3,4,5,6,8,9,12,20,25};\n\n        // 功能测试：not Found\n        int target1 = 30;\n        Assert.assertEquals(notFound, BinarySearch.binarySearch(arr2, target1));\n\n        // 功能测试：Found\n        int target2 = 5;\n        int expected = 2;\n        Assert.assertEquals(expected, BinarySearch.binarySearch(arr2, target2));\n    }\n\n    @Test\n    public void testBinarySearchRecur() {\n        int notFound = -1;\n        int target = 6;\n\n        // 测试数组为null\n        int[] arr = null;\n        Assert.assertEquals(notFound, BinarySearch.binarySearchRecur(arr, target));\n\n        // 测试数组为空\n        int[] arr1 = new int[0];\n        Assert.assertEquals(notFound, BinarySearch.binarySearchRecur(arr1, target));\n\n        // 功能测试\n        int[] arr2 = new int[] {3,4,5,6,8,9,12,20,25};\n\n        // 功能测试：not Found\n        int target1 = 30;\n        Assert.assertEquals(notFound, BinarySearch.binarySearchRecur(arr2, target1));\n\n        // 功能测试：Found\n        int target2 = 5;\n        int expected = 2;\n        Assert.assertEquals(expected, BinarySearch.binarySearchRecur(arr2, target2));\n    }\n\n    // 以下只进行功能测试\n    @Test\n    public void testBsFirst() {\n        int[] arr = new int[] {3,4,5,5,5,6,8,9,12,20,25};\n        int target = 5;\n        int expected = 2;\n\n        Assert.assertEquals(expected, BinarySearch.bsFirst(arr, target));\n\n        int target1 = 6;\n        int expected1 = 5;\n        Assert.assertEquals(expected1, BinarySearch.bsFirst(arr, target1));\n\n        int target2 = 30;\n        int expected2 = -1;\n        Assert.assertEquals(expected2, BinarySearch.bsFirst(arr, target2));\n    }\n\n    @Test\n    public void testBsLast() {\n        int[] arr = new int[] {3,4,5,5,5,6,8,9,12,20,25};\n        int target = 5;\n        int expected = 4;\n\n        Assert.assertEquals(expected, BinarySearch.bsLast(arr, target));\n\n        int target1 = 6;\n        int expected1 = 5;\n        Assert.assertEquals(expected1, BinarySearch.bsLast(arr, target1));\n\n        int target2 = 30;\n        int expected2 = -1;\n        Assert.assertEquals(expected2, BinarySearch.bsLast(arr, target2));\n    }\n\n    @Test\n    public void testBsFirstGE() {\n        int[] arr = new int[] {3,4,5,5,5,6,8,9,12,20,25};\n        int target = 5;\n        int expected = 2;\n\n        Assert.assertEquals(expected, BinarySearch.bsFistGE(arr, target));\n\n        int target1 = 7;\n        int expected1 = 6;\n        Assert.assertEquals(expected1, BinarySearch.bsFistGE(arr, target1));\n\n        int target2 = 30;\n        int expected2 = -1;\n        Assert.assertEquals(expected2, BinarySearch.bsFistGE(arr, target2));\n    }\n\n    @Test\n    public void testBsLastLE() {\n        int[] arr = new int[] {3,4,5,5,5,6,8,9,12,20,25};\n        int target = 5;\n        int expected = 4;\n\n        Assert.assertEquals(expected, BinarySearch.bsLastLE(arr, target));\n\n        int target1 = 7;\n        int expected1 = 5;\n        Assert.assertEquals(expected1, BinarySearch.bsLastLE(arr, target1));\n\n        int target2 = -2;\n        int expected2 = -1;\n        Assert.assertEquals(expected2, BinarySearch.bsLastLE(arr, target2));\n    }\n}\n"
  },
  {
    "path": "algorithms/src/array/GenericArray.java",
    "content": "package array;\n\n/**\n * 泛型动态数组\n *\n * @param <T>\n *\n */\n\npublic class GenericArray<T> {\n    private T[] data;\n    private int size; //数组当前元素个数,保证其可用范围为[0, size]\n\n    // 根据传入容量，构造Array\n    public GenericArray(int capacity) {\n        this.data = (T[]) new Object[capacity];\n        this.size = 0;\n    }\n\n    // 无参构造方法，默认数组容量为10\n    public GenericArray() {\n        this(10);\n    }\n\n    // 获取数组容量\n    public int getCapacity() {\n        return data.length;\n    }\n\n    // 获取当前数组元素个数\n    public int getSize() {\n        return size;\n    }\n\n    // 判断数组是否为空\n    public boolean isEmpty() {\n        return size == 0;\n    }\n\n    // 修改 index 位置的元素\n    public void set(int index, T e) {\n        checkIndex(index);\n        data[index] = e;\n    }\n\n    // 获取对应 index 位置的元素\n    public T get(int index) {\n        checkIndex(index);\n        return data[index];\n    }\n\n    // 查看数组是否包含元素e\n    public boolean contains(T e) {\n        for (int i = 0; i < size; i++) {\n            if (data[i].equals(e)) {   // 注意这里\n                return true;\n            }\n        }\n\n        return false;\n    }\n\n\n    // 获取对应元素的下标, 未找到，返回 -1\n    public int find(T e) {\n        for (int i = 0; i < size; i++) {\n            if (data[i].equals(e)) {\n                return i;\n            }\n        }\n        return -1;\n    }\n\n\n    // 在 index 位置，插入元素e, 时间复杂度 O(m+n)\n    public void add(int index, T e) {\n        checkIndex(index);\n        if (size == data.length) {\n            resize(2 * size);\n        }\n        for (int i = size - 1; i >= index; i++) {\n            data[i+1] = data[i];\n        }\n        data[index] = e;\n        size++;\n    }\n\n    // 向数组头插入元素\n    public void addFirst(T e) {\n        add(0, e);\n    }\n\n    // 向数组尾插入元素\n    public void addLast(T e) {\n        add(size, e);\n    }\n\n    // 删除 index 位置的元素，并返回\n    public T remove(int index) {\n        checkIndexForRemove(index);\n        T ret = data[index];\n        for (int i = index; i < size; i++) {\n            data[i] = data[i+1];\n        }\n        size--;\n\n        // 缩小容量\n        if (size == data.length / 4 && data.length / 2 != 0) {\n            resize(data.length / 2);\n        }\n\n        return ret;\n    }\n\n    // 删除第一个元素\n    public T removeFirst() {\n        return remove(0);\n    }\n\n    // 删除末尾元素\n    public T removeLast() {\n        return remove(size-1);\n    }\n\n    // 从数组中删除指定元素\n    public void removeElement(T e) {\n        int index = find(e);\n        if (index != -1) {\n            remove(index);\n        }\n    }\n\n    @Override\n    public String toString() {\n        StringBuilder builder = new StringBuilder();\n        builder.append(String.format(\"Array size = %d, capacity = %d \\n\", size, data.length));\n        builder.append('[');\n        for (int i = 0; i < size; i++) {\n            builder.append(data[i]);\n            if (i != size - 1) {\n                builder.append(\", \");\n            }\n        }\n        builder.append(']');\n        return builder.toString();\n    }\n\n\n    // 扩容方法，时间复杂度 O(n)\n    private void resize(int capacity) {\n        T[] temp = (T[]) new Object[capacity];\n        for (int i = 0; i < data.length; i++) {\n            temp[i] = data[i];\n        }\n        data = temp;\n    }\n\n    private void checkIndex(int index) {\n        if (index < 0 || index > size) {\n            throw new IllegalArgumentException(\"Add failed! Require index >= 0 and index <= size.\");\n        }\n    }\n\n    private void checkIndexForRemove(int index) {\n        if (index < 0 || index >= size) {\n            throw new IllegalArgumentException(\"Remove failed! Require index >= 0 and index < size.\");\n        }\n    }\n}\n\n\n\n"
  },
  {
    "path": "algorithms/src/array/MinNumberInRotatedArray.java",
    "content": "package array;\n\npublic class MinNumberInRotatedArray {\n\n    public static int getMinNumber(int[] arr) {\n        if (arr == null || arr.length < 1) {\n            throw new IllegalArgumentException(\"Invalid Array!\");\n        }\n\n        // 循环不变条件 [左侧递增数组 | 右侧递增数组]\n        int l = 0;                 // l始终指向左侧递增数组\n        int r = arr.length-1;      // r始终指向右侧递增数组\n\n        while (arr[l] >= arr[r]) {\n            if (r - l == 1) {\n                return arr[r];\n            }\n\n            int mid = l + ((r-l) >> 1);\n\n            // 若 arr[l] == arr[r] && arr[l] == arr[mid],\n            // arr[mid]无法判定属于左侧递增数组还是右侧递增数组，因此只能顺序查找\n            if (arr[l] == arr[r] && arr[l] == arr[mid]) {\n                return getMinInOrder(arr, l, r);\n            }\n\n            if (arr[mid] >= arr[l]) {\n                l = mid;\n            } else if (arr[mid] <= arr[r]) {\n                r = mid;\n            }\n        }\n\n        return arr[l]; // 若数组是已经排序的数组（从小到大），min = arr[l]。\n    }\n\n    private static int getMinInOrder(int[] arr, int l, int r) {\n        int min = arr[l];\n        for (int i = l+1 ; i <= r; i++) {\n            if (arr[i] < min) {\n                min = arr[i];\n            }\n        }\n\n        return min;\n    }\n}\n"
  },
  {
    "path": "algorithms/src/array/MinNumberInRotatedArrayTest.java",
    "content": "package array;\n\nimport org.junit.Assert;\nimport org.junit.Test;\n\npublic class MinNumberInRotatedArrayTest {\n\n    @Test\n    public void testGetMinNumber() {\n        int[] arr = new int[] {3,4,5,1,2};\n        int expected = 1;\n        Assert.assertEquals(expected, MinNumberInRotatedArray.getMinNumber(arr));\n\n        int[] arr1 = new int[] {1,2,3,4,5};\n        Assert.assertEquals(expected, MinNumberInRotatedArray.getMinNumber(arr1));\n\n        int[] arr2 = new int[] {1,0,1,1,1};\n        int expected1 = 0;\n        Assert.assertEquals(expected1, MinNumberInRotatedArray.getMinNumber(arr2));\n\n        int[] arr3 = new int[] {1,1,1,0,1};\n        Assert.assertEquals(expected1, MinNumberInRotatedArray.getMinNumber(arr3));\n    }\n}\n"
  },
  {
    "path": "algorithms/src/joseph/Joseph.java",
    "content": "package joseph;\n\n/**\n * Joseph Question\n *\n * Solution: 圆圈长度为n时的解f(n,m)可以看成是圆圈长度为n-1时的解f(n-1,m)加m。\n * 但是因为是循环的（圆圈），因此需要对相应的长度取余。\n * f(n,m) = (f(n-1,m) + m) % n n > 1\n * f(n,m) = 0                  n = 1\n *\n * 如：要解决n = 5, m = 3的情形：\n * n = 1: 0                    0\n * n = 2: 0,1             (0+3)%2 = 1;\n * n = 3: 0,1,2           (1+3)%3 = 1;\n * n = 4: 0,1,2,3         (1+3)%4 = 0;\n * n = 5: 0,1,2,3,4       (0+3)%5 = 3;\n */\npublic class Joseph {\n    public int lastRemain(int n, int m) {\n        if (n < 1 || m < 1) {\n            return -1;\n        }\n\n        if (n == 1) {\n            return 0;\n        }\n\n        return (lastRemain(n-1, m) + m) % n;\n    }\n\n    public int lastRemainIter(int n, int m) {\n        if (n < 1 || m < 1) {\n            return -1;\n        }\n\n        int last = 0;\n        for (int i = 2; i <= n; i++) {\n            last = (last + m) % i;\n        }\n\n        return last;\n    }\n}\n"
  },
  {
    "path": "algorithms/src/linkedlist/FindMidNode.java",
    "content": "package linkedlist;\n\npublic class FindMidNode {\n\n    // 1. T(n) = O(2*n) 遍历2次\n    public static Node findMidNode(Node head) {\n        if (head == null) {\n            return null;\n        }\n\n        int len = 0;\n        Node p = head;\n\n        while(p != null) {\n            len++;\n            p = p.next;\n        }\n\n        p = head;\n        for (int i = 0; i < len/2; i++) {\n            p = p.next;\n        }\n\n        return p;\n    }\n\n    // 2. T(n) = O(n) 遍历1次\n    // 快慢指针法\n    public static Node findMidNodeFast(Node head) {\n        if (head == null) {\n            return null;\n        }\n\n        Node fast = head;\n        Node slow = head;\n\n        while (fast != null && fast.next != null) {\n            fast = fast.next.next;\n            slow = slow.next;\n        }\n\n        return slow;\n    }\n\n\n    public static Node createNode(int value) {\n        return new Node(value, null);\n    }\n\n    public static class Node {\n        public int data;\n        public Node next;\n\n        public Node(int data, Node next) {\n            this.data = data;\n            this.next = next;\n        }\n    }\n}\n"
  },
  {
    "path": "algorithms/src/linkedlist/FindMidNodeTest.java",
    "content": "package linkedlist;\n\nimport org.junit.Assert;\nimport org.junit.Test;\n\n\npublic class FindMidNodeTest {\n\n    @Test\n    public void testFindMidNode() {\n        FindMidNode.Node head = FindMidNode.createNode(0);\n        head.next = FindMidNode.createNode(1);\n        head.next.next = FindMidNode.createNode(2);\n        head.next.next.next = FindMidNode.createNode(3);\n        head.next.next.next.next = FindMidNode.createNode(4); //[0,1,2,3,4]\n        FindMidNode.Node node1 = FindMidNode.findMidNode(head);\n        head.next.next.next.next.next = FindMidNode.createNode(5); //[0,1,2,3,4,5]\n        FindMidNode.Node node2 = FindMidNode.findMidNode(head);\n\n        int expected1 = 2;\n        int expected2 = 3;\n        Assert.assertEquals(expected1, node1.data);\n        Assert.assertEquals(expected2, node2.data);\n    }\n\n    @Test\n    public void testFindMidNodeFast() {\n        FindMidNode.Node head = FindMidNode.createNode(0);\n        head.next = FindMidNode.createNode(1);\n        head.next.next = FindMidNode.createNode(2);\n        head.next.next.next = FindMidNode.createNode(3);\n        head.next.next.next.next = FindMidNode.createNode(4); //[0,1,2,3,4]\n        FindMidNode.Node node1 = FindMidNode.findMidNodeFast(head);\n        head.next.next.next.next.next = FindMidNode.createNode(5); //[0,1,2,3,4,5]\n        FindMidNode.Node node2 = FindMidNode.findMidNodeFast(head);\n\n        int expected1 = 2;\n        int expected2 = 3;\n        Assert.assertEquals(expected1, node1.data);\n        Assert.assertEquals(expected2, node2.data);\n    }\n}\n"
  },
  {
    "path": "algorithms/src/linkedlist/SingleLinkedList.java",
    "content": "package linkedlist;\n\npublic class SingleLinkedList {\n\n    private Node head = null;\n\n    // 1. search\n    public Node findByValue(int value) {\n        if (head == null) {\n            return null;\n        }\n\n        for (Node p = head; p != null; p = p.next) {\n            if (p.data == value) return p;\n        }\n\n        return null;\n    }\n\n    public Node findByIndex(int index) {\n        if (head == null || index < 0) {\n            return null;\n        }\n\n        int temp = 0;\n        for (Node p = head; p != null; p = p.next) {\n            if (temp == index) return p;\n            temp++;\n        }\n\n        return null;\n    }\n\n    // 2. Insert\n    public void insertToHead(int value) {\n        Node newNode = createNode(value);\n        insertToHead(newNode);\n    }\n\n    public void insertToHead(Node newNode) {\n        if (newNode == null) {\n            return;\n        }\n\n        newNode.next = head;\n        head = newNode;\n    }\n\n    public void insertToTail(int value) {\n        Node newNode = createNode(value);\n        insertToTail(newNode);\n    }\n\n    public void insertToTail(Node newNode) {\n        if (newNode == null) {\n            return;\n        }\n\n        if (head == null) {\n            head = newNode;\n            return;\n        }\n\n        Node temp = head;\n        while (temp.next != null) {\n            temp = temp.next;\n        }\n\n        temp.next = newNode;\n    }\n\n\n    public void insertAfter(Node p, int value) {\n        Node newNode = createNode(value);\n        insertAfter(p, newNode);\n    }\n\n    public void insertAfter(Node p, Node newNode) {\n        if (p == null || newNode == null) {\n            return;\n        }\n\n        newNode.next = p.next;\n        p.next = newNode;\n    }\n\n    public void insertBefore(Node p, int value) {\n        Node newNode = createNode(value);\n        insertBefore(p, newNode);\n    }\n\n    public void insertBefore(Node p, Node newNode) {\n        if (p == null || newNode == null) {\n            return;\n        }\n\n        if (p == head) {\n            insertToHead(newNode);\n            return;\n        }\n\n        Node before = head;\n        while (before.next != p) {\n            before = before.next;\n        }\n\n        if (before == null) {\n            return;\n        } else {\n            newNode.next = p;\n            before.next = newNode;\n        }\n    }\n\n    // 3. delete\n    public void deleteByNode(Node p) {\n        if (head == null || p == null) {\n            return;\n        }\n\n        if (p == head) {\n            head = head.next;\n            return;\n        }\n\n        Node before = head;\n        while (before.next != p) {\n            before = before.next;\n        }\n\n        if (before == null) {\n            return;\n        } else {\n            before.next = p.next;\n        }\n    }\n\n    public void deleteByValue(int value) {\n        Node before = null;\n        for (Node p = head; p != null; p = p.next) {\n            if (p.getData() == value) {\n                if (p == head) {\n                    head = head.next;\n                    p = head;\n                } else {\n                    before.next = p.next;\n                    p = before;\n                }\n            }\n            before = p;\n        }\n    }\n\n    public void printAll() {\n        System.out.print(\"SingleLinkedList: [\");\n        for (Node p = head; p != null; p = p.next) {\n            System.out.print(p.getData());\n            if (p.next != null) {\n                System.out.print(\",\");\n            }\n        }\n        System.out.print(\"]\");\n        System.out.println();\n    }\n\n\n    public static Node createNode(int value) {\n        return new Node(value, null);\n    }\n\n    public static class Node {\n        private int data;\n        private Node next;\n\n        public Node(int data, Node next) {\n            this.data = data;\n            this.next = next;\n        }\n\n        public int getData() {\n            return data;\n        }\n    }\n}\n\n\n"
  },
  {
    "path": "algorithms/src/linkedlist/SingleLinkedListTest.java",
    "content": "package linkedlist;\n\nimport org.junit.Test;\n\npublic class SingleLinkedListTest {\n\n    @Test\n    public void testSingleLinkedList() {\n        SingleLinkedList list = new SingleLinkedList(); //[]\n        list.insertToTail(2);\n        list.insertToTail(3);\n        list.insertToTail(4);  // [2,3,4]\n        list.printAll();\n\n        list.insertToHead(1);\n        list.insertToHead(0); // [0,1，2,3,4]\n        list.printAll();\n\n        SingleLinkedList.Node node = list.findByIndex(2);\n        list.insertBefore(node, 10);\n        list.insertAfter(node, 10); // [0,1,10,2,10,3,4]\n        list.printAll();\n\n        list.deleteByValue(10);\n        list.printAll(); // [0,1，2,3,4]\n\n        SingleLinkedList.Node p = list.findByValue(2);\n        System.out.println(node.getData() == p.getData()); // true\n    }\n}\n"
  },
  {
    "path": "algorithms/src/lru/LRU.java",
    "content": "package lru;\n\nimport java.util.HashMap;\nimport java.util.Iterator;\n\n/**\n * LRU Cache: 优先淘汰最久未使用的数据\n * Solution: 双向链表+HashMap\n * 1. 访问某个节点时，将其从原来的位置删除，并且重新插入到链表头部（保证链表尾部存储最近最久未使用的节点）。当节点数量大于缓存的\n * 最大空间时，就淘汰链表尾部的节点。使用双端链表是为了保证删除操作时间复杂度为O(1)。\n * 2. 为了使得删除操作的时间复杂度是O(1),就不能使用遍历的方式找到某个节点。HashMap存储的是Key到节点的映射，通过Key就能够以O(1)\n * 的时间得到节点，然后再以O(1)的时间将其从双向队列中删除。\n * 具体步骤：\n * 1. get(): \n * 访问某个节点时，若这个节点不存在，返回null; \n * 若这个节点存在，则将该节点从该位置删除，然后插入到链表头部，最后返回该节点的值。\n * 2. put():\n * 插入节点时，若这个节点存在，则将这个节点从原位置删除，然后插入到链表头部。\n * 若这个节点不存在，则新建一个节点，然后将这个节点插入链表头部，然后将该节点插入到map中\n * 此时，若map中节点的数量大于cache的容量，则将该链表尾部节点删除，同时在map中删除链表尾部节点。\n * \n * Example:\n * head <-> 1,1 <-> 2,2 <-> 3,3 <-> tail;\n * put(2,2): head <-> 2,2 <-> 1,1 <-> 3,3 <-> tail;\n * get(3):   head <-> 3,3 <-> 2,2 <-> 1,1 <-> tail;\n *\n * @param <K>\n * @param <V>\n */\npublic class LRU<K,V> implements Iterable<K> {\n\n    private Node head;\n    private Node tail;\n    private HashMap<K, Node> map;\n    private int maxSize;\n\n\n    private class Node {\n        Node pre;\n        Node next;\n        K k;\n        V v;\n\n        public Node(K k, V v) {\n            this.k = k;\n            this.v = v;\n        }\n    }\n\n    public LRU(int maxSize) {\n        this.maxSize = maxSize;\n        this.map = new HashMap<>(maxSize * 4 / 3);\n\n        head = new Node(null, null);\n        tail = new Node(null, null);\n\n        head.next = tail;\n        tail.pre = head;\n    }\n\n    // O(1)\n    public V get(K key) {\n        if (!map.containsKey(key)) {\n            return null;\n        }\n\n        Node node = map.get(key);\n        unlink(node);\n        appendToHead(node);\n\n        return node.v;\n    }\n\n    // O(1)\n    public void put(K key, V value) {\n        if (map.containsKey(key)) {\n            Node node = map.get(key);\n            unlink(node);\n        }\n\n        Node node = new Node(key, value);\n        appendToHead(node);\n        map.put(key, node);\n\n        if (map.size() > maxSize) {\n            Node toRemove = removeTail();\n            map.remove(toRemove.k);\n        }\n    }\n\n    private Node removeTail() {\n        Node node = tail.pre;\n\n        Node pre = node.pre;\n        tail.pre = pre;\n        pre.next = tail;\n\n        node.next = null;\n        node.pre = null;\n\n        return node;\n    }\n\n    private void appendToHead(Node node) {\n        Node next = head.next;\n        node.next = next;\n        node.pre = head;\n\t\t\n\t\tnext.pre = node;\n        head.next = node;\n    }\n\n    private void unlink(Node node) {\n        Node pre = node.pre;\n        Node next = node.next;\n\n        pre.next = next;\n        next.pre = pre;\n\n        node.pre = null;\n        node.next = null;\n    }\n\n    @Override\n    public Iterator<K> iterator() {\n        return new LRUIterator<>();\n    }\n\n    private class LRUIterator<K> implements Iterator<K> {\n        private Node cur = head.next;\n\n        @Override\n        public boolean hasNext() {\n            return cur != tail;\n        }\n\n        @Override\n        public K next() {\n            Node node = cur;\n            cur = cur.next;\n            return (K) node.k;\n        }\n    }\n\n}\n"
  },
  {
    "path": "algorithms/src/lru/LRUTest.java",
    "content": "package lru;\n\nimport org.junit.Assert;\nimport org.junit.Test;\n\npublic class LRUTest {\n    @Test\n    public void testLRU() {\n        LRU<Integer, Integer> lru = new LRU<>(5);\n        Assert.assertEquals(null, lru.get(1));\n\n        lru.put(1,1);\n        Assert.assertEquals(Integer.valueOf(1), lru.get(1));\n        lru.put(2,2);\n        lru.put(3,3);\n        lru.put(4,4);\n        lru.put(5,5);\n        for (Integer integer : lru) {\n            System.out.print(integer + \" \");\n        }\n\n        System.out.println();\n\n        Assert.assertEquals(Integer.valueOf(2), lru.get(2));\n        for (Integer integer : lru) {\n            System.out.print(integer + \" \");\n        }\n\n        System.out.println();\n\n        lru.put(6,6);\n        for (Integer integer : lru) {\n            System.out.print(integer + \" \");\n        }\n    }\n}\n"
  },
  {
    "path": "algorithms/src/queue/ArrayQueue.java",
    "content": "package queue;\n\npublic class ArrayQueue<T> implements Queue<T> {\n    private T[] items;\n    private int capacity;\n    private int head;\n    private int tail;\n\n    public ArrayQueue(int capacity) {\n        this.capacity = capacity;\n        this.items = (T[]) new Object[capacity];\n        this.head = 0;\n        this.tail = 0;\n    }\n\n    // T(N)=O(1)\n    @Override\n    public boolean enqueue(T item) {\n        if (tail == capacity) {\n            // head == 0 && tail == capacity, queue is full.\n            if (head == 0) {\n                return false;\n            }\n\n            // 数据搬移，空出位置\n            for (int i = head; i < tail; i++) {\n                items[i-head] = items[i];\n            }\n\t\t\t\n            // 搬移完之后，更新head和tail\n\t        tail -= head;\n\t        head = 0;\n        }\n\n        items[tail] = item;\n        tail++;\n\n        return true;\n    }\n\n    // T(N)=O(1)\n    @Override\n    public T dequeue() {\n        if (head == tail) {\n            return null;\n        }\n\n        T tmp = items[head];\n        head++;\n\n        return tmp;\n    }\n\n    // for test\n    public void printAll() {\n        System.out.print(\"[\");\n        for (int i = head;  i < tail; i++) {\n            System.out.print(items[i] + \" \");\n        }\n        System.out.print(\"]\");\n        System.out.println();\n    }\n\n    public static void main(String[] args) {\n        ArrayQueue<String> queue = new ArrayQueue<>(4);\n        queue.printAll();\n        queue.enqueue(\"A\");\n        queue.printAll();\n        queue.enqueue(\"B\");\n        queue.enqueue(\"C\");\n        queue.enqueue(\"D\");\n        queue.printAll();\n        queue.enqueue(\"E\");\n        queue.printAll();\n\n        queue.dequeue();\n        queue.dequeue();\n        queue.dequeue();\n        queue.printAll();\n    }\n}\n"
  },
  {
    "path": "algorithms/src/queue/CircularQueue.java",
    "content": "package queue;\n\npublic class CircularQueue<T> {\n    private T[] items;\n    private int capacity;\n    private int head;\n    private int tail;\n\n    public CircularQueue(int capacity) {\n        this.capacity = capacity;\n        this.items = (T[]) new Object[capacity];\n        this.head = 0;\n        this.tail = 0;\n    }\n\n    // T(N)=O(1)\n    public boolean enqueue(T item) {\n        // 队满条件\n        if ((tail + 1) % capacity == head) {\n            return false;\n        }\n\n        items[tail] = item;\n        tail = (tail + 1) % capacity;\n        return true;\n    }\n\n    // T(N)=O(1)\n    public T dequeue() {\n        // 队空条件\n        if (head == tail) {\n            return null;\n        }\n\n        T tmp = items[head];\n        items[head] = null;  // 这里可以选择置为nulL,也可以不置为null.\n        head = (head + 1) % capacity;\n\n        return tmp;\n    }\n\n    // for test\n    public void printAll() {\n        System.out.print(\"[\");\n        for (int i = 0;  i < capacity; i++) {\n            System.out.print(items[i] + \" \");\n        }\n        System.out.print(\"]\");\n        System.out.println();\n    }\n\n    public static void main(String[] args) {\n        CircularQueue<java.lang.String> queue = new CircularQueue<>(4);\n        queue.printAll();\n        queue.enqueue(\"A\");\n        queue.printAll();\n        queue.enqueue(\"B\");\n        queue.enqueue(\"C\");\n        queue.enqueue(\"D\");\n        queue.printAll();\n        queue.enqueue(\"E\");\n        queue.printAll();\n\n        queue.dequeue();\n        queue.dequeue();\n        queue.enqueue(\"E\");\n        queue.printAll();\n    }\n}\n"
  },
  {
    "path": "algorithms/src/queue/ListQueue.java",
    "content": "package queue;\n\npublic class ListQueue<T> implements Queue<T> {\n\n    Node head = null;\n    Node tail = null;\n\n    // T(N)=O(1)\n    @Override\n    public boolean enqueue(T item) {\n        Node newNode = new Node(item, null);\n        if (tail == null) {\n            tail = newNode;\n            head = newNode;\n            return true;\n        }\n\n        tail.next = newNode;\n        tail = tail.next;\n\n        return true;\n    }\n\n    // T(N)=O(1)\n    @Override\n    public T dequeue() {\n        if (head == null) {\n            return null;\n        }\n\n        Node tmp = head;\n        head = head.next;\n        tmp.next = null;\n\n        return (T) tmp.getData();\n    }\n\n    // for test\n    public void printAll() {\n        System.out.print(\"[\");\n        for (Node p = head; p != null; p = p.next) {\n            System.out.print(p.getData() + \" \");\n        }\n        System.out.print(\"]\");\n        System.out.println();\n    }\n\n    private static class Node<T>{\n        private T data;\n        private Node next;\n\n        public Node(T data, Node next) {\n            this.data = data;\n            this.next = next;\n        }\n\n        public T getData() {\n            return this.data;\n        }\n    }\n\n    public static void main(String[] args) {\n        ListQueue<String> queue = new ListQueue<>();\n        queue.printAll();\n        queue.enqueue(\"A\");\n        queue.printAll();\n        queue.enqueue(\"B\");\n        queue.enqueue(\"C\");\n        queue.enqueue(\"D\");\n        queue.printAll();\n        queue.enqueue(\"E\");\n        queue.printAll();\n\n        queue.dequeue();\n        queue.dequeue();\n        queue.dequeue();\n        queue.printAll();\n    }\n}\n"
  },
  {
    "path": "algorithms/src/queue/Queue.java",
    "content": "package queue;\n\npublic interface Queue<T> {\n    boolean enqueue(T item);\n    T dequeue();\n}\n"
  },
  {
    "path": "algorithms/src/stack/ArrayStack.java",
    "content": "package stack;\n\npublic class ArrayStack<T> implements Stack<T> {\n    private T[] items;     // 数组\n    private int top;       // 栈中元素的个数（或者说是栈顶指针）\n    private int capacity;  // 栈的容量\n\n\n    public ArrayStack(int capacity) {\n        this.capacity = capacity;\n        this.items = (T[]) new Object[capacity];\n        this.top = 0;\n    }\n\n    // T(N)=O(1)\n    @Override\n    public boolean push(T item) {\n        // 数组空间不足，无法push\n        if (top == capacity) {\n            return false;\n        }\n\n        // size为待push的位置\n        items[top] = item;\n        top++;\n\n        return true;\n    }\n\n    // T(N)=O(1)\n    @Override\n    public T pop() {\n        // 数组为空，无法pop\n        if (top == 0) {\n            return null;\n        }\n\n        T item = items[top -1];\n        top--;\n\n        return item;\n    }\n\n    // T(N)=O(1)\n    @Override\n    public T peek() {\n        if (top == 0) {\n            return null;\n        }\n        return items[top -1];\n    }\n\n    public static void main(String[] args) {\n        ArrayStack<String> stack = new ArrayStack<>(4);\n        stack.push(\"A\");\n        stack.push(\"B\");\n        stack.push(\"C\");\n        stack.push(\"D\");\n        System.out.println(stack.peek());\n        stack.pop();\n        System.out.println(stack.peek());\n        stack.pop();\n        stack.pop();\n        stack.pop();\n        stack.pop();\n        System.out.println(stack.peek());\n    }\n}\n"
  },
  {
    "path": "algorithms/src/stack/DynamicArrayStack.java",
    "content": "package stack;\n\n/**\n * 支持动态扩容的栈\n *\n * @param <T>\n */\npublic class DynamicArrayStack<T> implements Stack<T> {\n    private T[] items;\n    private int top;\n    private int capacity;\n\n    public DynamicArrayStack(int capacity) {\n        this.capacity = capacity;\n        this.items = (T[]) new Object[capacity];\n        this.top = 0;\n    }\n\n    // T(N)=O(1): 思考一下，这里涉及到了数组的动态扩容，\n    // 那么时间复杂度为什么仍然是O(1)\n    @Override\n    public boolean push(T item) {\n        if (top == capacity) {\n            capacity = capacity * 2;\n            resize(capacity);\n        }\n\n        items[top] = item;\n        top++;\n\n        return false;\n    }\n\n    // T(N)=O(1)\n    @Override\n    public T pop() {\n        if (top == 0) {\n            return null;\n        }\n\n        T item = items[top -1];\n        top--;\n\n        return item;\n    }\n\n    // T(N)=O(1)\n    @Override\n    public T peek() {\n        if (top == 0) {\n            return null;\n        }\n        return items[top -1];\n    }\n\n    private void resize(int size) {\n        T[] tmp = (T[]) new Object[size];\n        for (int i = 0; i < items.length; i++) {\n            tmp[i] = this.items[i];\n        }\n\n        this.items = tmp;\n    }\n\n    public static void main(String[] args) {\n        DynamicArrayStack<String> stack = new DynamicArrayStack<>(4);\n        stack.push(\"A\");\n        stack.push(\"B\");\n        stack.push(\"C\");\n        stack.push(\"D\");\n        System.out.println(stack.peek());\n        stack.push(\"E\");\n        System.out.println(stack.peek());\n        stack.pop();\n        System.out.println(stack.peek());\n        stack.pop();\n        stack.pop();\n        stack.pop();\n        stack.pop();\n        System.out.println(stack.peek());\n    }\n}\n"
  },
  {
    "path": "algorithms/src/stack/ListStack.java",
    "content": "package stack;\n\npublic class ListStack<T> implements Stack<T> {\n    private Node top = null;\n\n    // T(N)=O(1)\n    @Override\n    public boolean push(T item) {\n        Node newNode = new Node(item, null);\n\n        // 需要判断栈是否为空\n        if (top == null) {\n            top = newNode;\n        } else {\n            newNode.next = top;\n            top = newNode;\n        }\n        return true;\n    }\n\n    // T(N)=O(1)\n    @Override\n    public T pop() {\n        if (top == null) {\n            return null;\n        }\n\n        Node tmp = top;\n\n        top = top.next;\n        tmp.next = null;  // 释放删除的top\n\n        return (T) tmp.getData();\n    }\n\n    // T(N)=O(1)\n    @Override\n    public T peek() {\n        if (top == null) {\n            return null;\n        }\n        return (T) top.getData();\n    }\n\n    public static class Node<T> {\n        private T data;\n        private Node next;\n\n        public Node(T data, Node next) {\n            this.data = data;\n            this.next = next;\n        }\n\n        public T getData() {\n            return this.data;\n        }\n    }\n\n    public static void main(String[] args) {\n        ListStack<String> stack = new ListStack<>();\n        stack.push(\"A\");\n        stack.push(\"B\");\n        stack.push(\"C\");\n        stack.push(\"D\");\n        System.out.println(stack.peek());\n        stack.pop();\n        System.out.println(stack.peek());\n        stack.pop();\n        stack.pop();\n        stack.pop();\n        stack.pop();\n        System.out.println(stack.peek());\n    }\n}\n"
  },
  {
    "path": "algorithms/src/stack/SampleBrowser.java",
    "content": "package stack;\n\n/**\n * 浏览器页面的前进和后退功能\n */\npublic class SampleBrowser {\n\n    private String currentPage;\n//    private Stack backwardStack;\n    private Stac\n\n}\n"
  },
  {
    "path": "algorithms/src/stack/Stack.java",
    "content": "package stack;\n\npublic interface Stack<T> {\n    boolean push(T item);\n    T pop();\n    T peek();\n}\n"
  },
  {
    "path": "appendix/instructions.md",
    "content": "# 上传与更新本地代码到Github\n\n1. 远程操作：\n   * Github上创建Repo\n2. 本地操作：\n   * git clone https://github.com/guokaide/leetcode\n   * cd leetcode\n   * git init\n   * git add .\n   * git remote add origin https://github.com/guokaide/leetcode  （将本地仓库与远程关联）\n   * git commit -m \"update all files\"\n   * git pull origin master  (将remote所有的操作更新到本地，避免local与remote冲突)\n   * git push -u origin master\n3. 注：核心更新操作\n   * git status\n   * git add *\n   * git commit -m \"comments\"\n   * git pull origin master\n   * git push origin master\n\n"
  },
  {
    "path": "appendix/刷题笔记.md",
    "content": "# 刷题笔记\n\n> It does not matter how slowly you go as long as you do not stop.  \n\n## 如何有效学习数据结构与算法？\n\n### 如何精通一个领域？\n\n* Chunk it up  切碎知识点\n\n  将数据结构与算法的基本知识点分解开来，分解结果见：[数据结构与算法脑图]( http://naotu.baidu.com/file/cd094852bfc84ec5e1868867936451c3?token=ef906723267f2f9f )\n\n* Deliberate Practicing 刻意练习\n\n  对分解之后的知识点进行分解训练和反复练习。\n\n  * 明白一个`原则`：基本功是区别业余和职业选手的根本，我们的目标是成为职业选手。\n\n  * 明白一个`误区`：**刷一道算法题，刷一遍是完全不够的，需要一遍遍刷题**。\n  * 明白一个`事实`：反复练习自己薄弱的地方，扩张舒适区，会让我们成长更快。 \n\n* Feedback 反馈\n\n  反馈对于学习的作用，主要是将揉碎的知识点再串联起来，形成体系结构，这样就建立了一个 `知识点-> 专项反复练习-> 建立知识体系`的学习闭环。\n\n  * 即时反馈\n  * 主动型反馈（自己去找）\n    * 高手代码，例如 Github，LeetCode（题解、Discussion）\n    * 第一视角直播\n  * 被动式反馈（高手指点）\n    * Code Review\n    * 教练看你打，然后给你反馈\n\n### 如何精通数据结构与算法呢？\n\n> 如何反复刷题呢？答案是：五步刷题法，我们称为***五毒神掌***。\n\n1. 刷题第***1***遍\n   * 5分钟时间：读题+思考\n   * 若5分钟思考不出来，直接看解法，要注意：**对每一道题目，思考和比较这个题的多种解法，最好是全部解法**\n   * **背诵、默写好的解法**：这是积累代码能力的一个很好的办法。\n2. 刷题第***2***遍\n   * 马上自己写 -> LeetCode提交\n   * **多种解法进行比较、体会 -> 优化**\n3. 刷题第***3***遍\n   * **一天后**，再重复做题\n   * 针对不同解法的熟练程度 -> 对薄弱的地方进行专项练习\n4. 刷题第***4***遍\n   * **一周后**，反复回来练习相同的题目\n5. 刷题第***5***遍\n   * **面试前一周**进行恢复性训练。\n\n> 如何刷一道题呢？ 答案是：**切题四件套**。\n\n1.  Clarification: 多沟通，多思考，确保正确理解问题                     ***（面试的时候，和面试官过一遍题目）***\n2. Possible solutions: 思考关于这个题目的所有解法，比较其优劣，优化其性能\n   * compare(time/space)\n   * optimal(加强)：例如空间换时间、升维（一维到二维）    ***（提出多种解法，给出最优解法）***\n3. Coding: 就是不停的写，多写，提高Coding能力的唯一法宝       ***（代码实现）***\n4. Test cases                                                                                            ***（阐述测试样例）***\n\n## 工具\n\n### [visualgo](https://visualgo.net/zh)\n\n### [bigocheatsheet](https://www.bigocheatsheet.com/)\n\n## 代码模板\n\n### 递归代码模板 Recursion\n\n* Python\n\n  ```python\n  def recursion(level, param1, param2, ...): \n      # recursion terminator \n      if (level > MAX_LEVEL): \n  \t   # process result \n  \t   return \n  \n      # process logic in current level\n      process(level, data...) \n  \n      # drill down \n      self.recursion(level + 1, p1, ...) \n  \n      # restore current level status if needed\n  \n  ```\n\n* Java\n\n  ```java\n  public void recursion(int level, int param) { \n    // recursion terminator \n    if (level > MAX_LEVEL) { \n      // process result \n      return; \n    } \n  \n    // process logic in current level\n    process(level, param); \n  \n    // drill down \n    recursion( level: level + 1, newParam); \n  \n    // restore current level status if needed \n   \n  }\n  ```\n\n  \n\n### 分治代码模板 Divide and Conquer\n\n```python\ndef divide_conquer(problem, param1, param2, ...): \n  # recursion terminator \n  if problem is None: \n\tprint_result \n\treturn \n\n  # divide: prepare data \n  data = prepare_data(problem) \n  subproblems = split_problem(problem, data) \n\n  # conquer: conquer subproblems \n  subresult1 = self.divide_conquer(subproblems[0], p1, ...) \n  subresult2 = self.divide_conquer(subproblems[1], p1, ...) \n  subresult3 = self.divide_conquer(subproblems[2], p1, ...) \n  …\n\n  # merge: process and generate the final result \n  result = process_result(subresult1, subresult2, subresult3, …)\n\t\n  # restore current level states if needed\n\n```\n\n### 查找-搜索-遍历 模板\n查找的特点是：\n\n* 找到特定元素\n\n搜索的特点是：\n\n* 每个节点都要访问一次\n* 每个节点仅仅访问一次\n* 每个节点访问顺序不限\n\n#### 二分查找（Binary Search）\n\n```python\nleft, right = 0, len(array) - 1\nwhile left <= right:\n    mid = (left + right) / 2\n    if array[mid] == target:\n        # find the target\n        break or return result\n    elif array[mid] < target:\n        left = mid + 1\n    else:\n        right = mid - 1\n```\n\n#### 深度优先搜索（DFS, Depth First Search)\n\n```python\n# 递归写法\nvisited = set()\n\ndef dfs(node, visited):\n    # terminator\n    if node in visited:\n        return           # already visited\n    \n    visited.add(node)\n        \n    # process current node here\n    # ...\n    \n    for next_node in node.children():\n        if next_node not in visited:\n         \tdfs(next_node, visited)\n            \n# 非递归写法\ndef DFS(self, tree):\n    if tree.root is None:\n        return []\n    \n    visited, stack = [], [tree.root]\n   \t\n    while stack:\n        node = stack.pop()\n        visited.add(node)\n        \n        process(node)\n        \n        nodes = generate_realted_nodes(node)\n        stack.push(nodes)\n        \n    # other processing work\n    ...\n   \n```\n\n#### 广度优先遍历（BFS, Breadth First Search）\n\n```python\ndef BFS(graph, start, end):\n\tvisited = set()\n    queue = []\n    queue.append([start])\n    \n    while queue:\n        node = queue.pop()\n        visited.add(node)\n        \n        process(node)\n        \n        nodes = generate_related_nodes(node)\n        queue.push(nodes)\n    \n    # other processing work\n    ...         \n```\n\n#### A*\n\n```python\ndef AstarSearch(graph, start, end):\n\n\tpq = collections.priority_queue() # 优先级 —> 估价函数\n\tpq.append([start]) \n\tvisited.add(start)\n\n\twhile pq: \n\t\tnode = pq.pop() # can we add more intelligence here ?\n\t\tvisited.add(node)\n\n\t\tprocess(node) \n\t\tnodes = generate_related_nodes(node) \n   unvisited = [node for node in nodes if node not in visited]\n\t\tpq.push(unvisited)\n```\n\n\n\n### 归并排序\n\n### Trie\n\n#### 定义\n\nTrie 树，也叫“字典树”。Trie 树也是一种树形结构。它是专门用来处理字符串匹配的数据结构，**用来解决一组字符串集合中快速查找某个字符串的问题**。\n\n#### 本质\n\nTrie 树的本质，就是利用字符串之间的公共前缀，将重复的前缀合并在一起，组成一颗多个字符串共用前缀的树。这种存储方式避免了重复存储一组字符串的相同前缀子串。\n\n#### 实现\n\n##### API\n\n* void insert(char[] text)           // 插入字符串\n* boolean search(char[] pattern)     // 查找字符串\n* boolean startsWith(String prefix)  // 查找前缀\n\n##### 代码\n\n假设字符串由a~z这26个小写字母构成，数组下标为0的位置存储指向子节点a的的指针，下标为1的位置存储指向子节点b的指针，以此类推，下标为25的位置存储指向子节点z的指针。如果某个子节点不存在，则对应下边位置处存储为null。\n\n```java\npublic class TrieNode {\n    public char data;\n    public TrieNode[] children = new TrieNode[26];\n\tpublic boolean isEndingChar = false;\n    \n    public TrieNode(char data) {\n        this.data = data;\n    }\n}\n\npublic class Triee {\n    // 根节点,存储无意义字符\n    private TrieNode root = new TrieNode('/'); \n\t\n    // 插入字符串\n    public void insert(char[] text) {\n        TrieNode p = root;\n        for (int i = 0; i < text.length; ++i) {\n            int index = text[i] - 'a';\n            if (p.children[index] == null) {\n                TrieNode newNode = new TrieNode(text[i]);\n                p.children[index] = newNode;\n            }\n            p = p.children[index];\n        }\n        p.isEndingChar = true;\n    }\n    \n    // 查找字符串\n    public boolean search(char[] pattern) {\n        TrieNode p = root;\n        for (int i = 0; i < pattern.length; ++i) {\n            int index = pattern[i] - 'a';\n            if (p.children[index] == null) {\n                return false;\n            }\n            p = p.children[index];\n        }\n        if (p.isEndingChar == false) {\n            return false;   // pattern 仅仅是前缀， 无法完全匹配\n        } else {\n            return true;    // 完全匹配\n        }\n    }\n}\n```\n\n```python\nclass Trie(object):\n  \n\tdef __init__(self): \n\t\tself.root = {} \n\t\tself.end_of_word = \"#\" \n \n\tdef insert(self, word): \n\t\tnode = self.root \n\t\tfor char in word: \n\t\t\tnode = node.setdefault(char, {}) \n\t\tnode[self.end_of_word] = self.end_of_word \n \n\tdef search(self, word): \n\t\tnode = self.root \n\t\tfor char in word: \n\t\t\tif char not in node: \n\t\t\t\treturn False \n\t\t\tnode = node[char] \n\t\treturn self.end_of_word in node \n \n\tdef startsWith(self, prefix): \n\t\tnode = self.root \n\t\tfor char in prefix: \n\t\t\tif char not in node: \n\t\t\t\treturn False \n\t\t\tnode = node[char] \n\t\treturn True\n```\n\n[LeetCode 208. implement-trie-prefix-tree](https://leetcode-cn.com/problems/implement-trie-prefix-tree/)\n\n```java\nclass Trie {\n\n    private TrieNode root;\n\n    /** Initialize your data structure here. */\n    public Trie() {\n        this.root = new TrieNode('/');\n    }\n    \n    /** Inserts a word into the trie. */\n    public void insert(String word) {\n        TrieNode p = root;\n        for (int i = 0; i < word.length(); i++) {\n            int index = word.charAt(i) - 'a';\n            if (p.children[index] == null) {\n                TrieNode newNode = new TrieNode(word.charAt(i));\n                p.children[index] = newNode;\n            }\n            p = p.children[index];\n        }\n        p.isEndingChar = true;\n    }\n    \n    /** Returns if the word is in the trie. */\n    public boolean search(String word) {\n        TrieNode p = root;\n        for (int i = 0; i < word.length(); i++) {\n            int index = word.charAt(i) - 'a';\n            if (p.children[index] == null) {\n                return false;\n            }\n            p = p.children[index];\n        }\n        if (p.isEndingChar) return true;\n        else return false;\n    }\n    \n    /** Returns if there is any word in the trie that starts with the given prefix. */\n    public boolean startsWith(String prefix) {\n        TrieNode p = root;\n        for (int i = 0; i < prefix.length(); i++) {\n            int index = prefix.charAt(i) - 'a';\n            if (p.children[index] == null) {\n                return false;\n            }\n            p = p.children[index];\n        }\n        return true;\n    }\n\n    class TrieNode {\n        public char data;\n        public TrieNode[] children = new TrieNode[26];\n\t    public boolean isEndingChar = false;\n    \n        public TrieNode(char data) {\n            this.data = data;\n        }\n    }\n}\n\n/**\n * Your Trie object will be instantiated and called as such:\n * Trie obj = new Trie();\n * obj.insert(word);\n * boolean param_2 = obj.search(word);\n * boolean param_3 = obj.startsWith(prefix);\n */\n```\n\n\n\n#### 性能\n\n##### 时间复杂度\n\n如果在一组字符串中，频繁地查询某些字符串，用 Trie 树会非常高效。\n\n构建 Trie 树的过程，需要扫描所有的字符串，因此时间复杂度为 `O(N)`，其中`N` 为所有字符串长度之和。\n\n构建 Trie 树的过程，时间复杂度较高，但是一旦构建成功，后续查询操作会非常高效。每次查询时，若查询的字符串长度为`k`,那么我们只需要对比大约 `k`个节点，就能完成查询操作，与原来的那组字符串长度和个数都没有关系。因此，构建 Trie 树之后，查询操作的时间复杂度为 `O(k)`, 其中 `k` 表示要查找的字符串的长度。\n\n##### 空间复杂度\n\n从前面的实现，可以看出，Trie 树的每个节点都需要维护一个长度为26的数组，如果字符串不仅包含小写字母，而且还包含大写字母，数字以及中文等，那需要的存储空间就更多了。Trie 树本质是为了避免重复存储相同的公共前缀，但是在重复的前缀不多的情况下，Trie 树不但不能节省内存，还有可能会浪费更多的内存。\n\nTrie 树 是一种空间换时间的实现，尽管比较耗费空间，但是查找确实高效。\n\n#### Trie 树的应用\n\nTrie 树解决了在一组字符串集合中查找字符串的问题，相同的问题，我们其实还可以通过散列表或者红黑树解决。\n\n事实上，Trie 树在一组字符串中查找字符串的表现并不是很好，它对要处理的字符串有极其严苛的要求。\n\n1. 字符串中包含的字符集不能太大。字符集太大，将会浪费很多存储空间。\n2. 要求多个字符串前缀重合比较多，不然将会浪费很多存储空间。\n3. 通过指针穿起来的数据块是不连续的，而 Trie 树中用到了指针，所以对缓存不友好，性能上会打折扣。\n\n事实上，Trie 树只是不适合精确匹配查找，而且不适合用来做动态数据的查找，这种问题更加适合用散列表或者红黑树解决。 `Trie 树更加适合查找前缀匹配的字符串`，例如Google时的关键词提示功能，自动补全等功能，或者是统计单词频次等问题。\n\n\n\n### UnionFind\n\n```java\nclass UnionFind {\n    private int count = 0;\n    private int[] parent;\n    \n    /* 初始化为 n 个集合*/\n    public UnionFind(int n) {\n        count = n;\n        parent = new int[n];\n    \tfor (int i = 0; i < n; i++) {\n            parent[i] = i;\n        }\n    }\n    \n    /* 确定 q 属于哪个子集合 */\n    public int find(int p) {\n        while (p != parent[p]) {\n            parent[p] = parent[parent[p]];\n            p = parent[p];\n        }\n        return p;\n    }\n    \n    /* 合并 p 和 q 所在的集合*/\n    public void union(int p, int q) {\n        int rootP = find(p);\n        int rootQ = find(q);\n        if (rooP == rootQ) return;\n        parent[rootP] = rootQ;\n        count--;\n    }\n    \n}\n```\n\n```python\ndef init(p):\n    p = [i for i in range(n)]\n    \ndef union(self, p, i, j):\n    p1 = self.parent(p, i)\n    p2 = self.parent(p, j)\n    p[p1] = p2\n    \ndef parent(self, p, i):\n    root  = i;\n    while p[root] != root:\n        root = p[root] \n    while p[i] != i: # 路径压缩\n        x = i\n        i = p[i]\n        p[x] = root\n    return root\n```\n\n\n\n### 八皇后问题\n\nhttps://shimo.im/docs/hV9GdhcrddcDJWwv\n\n## Dynamic Programming\n\n> Simplifying a complicated problem by breaking it down into simpler sub-problems in a recursive manner\n\n### 动态规划基本理论\n\n#### 一个模型：多阶段决策最优解模型\n\n动态规划一般用于解决最优问题。多阶段决策最优解模型是指动态规划适合解决的问题的模型。解决问题的过程需要经历多个决策过程，每个决策过程都对应着一组状态。动态规划的目标在于寻找一组决策序列（每个决策过程的状态），通过这组决策序列产生最终期望的求解的最优值。\n\n\n\n#### 三个特征\n\n##### 最优子结构\n\n最优子结构是指问题的最优解包含子问题的最优解。我们可以通过子问题的最优解得到问题的最优解，也就是说，后面的状态可以通过前面的状态推导出来。\n\n##### 无后效性\n\n无后效性有两层含义：\n\n* 在推导后面状态的时候，我们只关心前面阶段的状态值，而不关心这个状态值的求解过程；\n* 某个阶段的状态一旦确定，就不受之后阶段的决策影响，即状态定了就定了。\n\n##### 重复子问题\n\n不同的决策序列，到达某个相同的阶段的时候，可能会产生重复的状态。 \n\n\n\n##### 复杂度\n\n1、状态存在更多的维度（二维、三维或者更多，甚至需要压缩）\n\n2、状态方程更加复杂\n\n\n\n#### 实例\n\n> 问题：给定一个`n * n`的矩阵` w[n][n]`，矩阵存储的均为正整数。棋子从矩阵的左上角出发去右下角，每次只能向右或者是向下移动1位。从左上角到右下角有很多不同的路径可以走。规定每条路径经过的数字之和就是这条路径的长度。求从左上角到右下角的最短路径。\n\n##### 分析：\n\n***这个问题是否满足`一个模型`呢？***\n\n从 `(0, 0)` 出发到 `(n-1, n-1)`，总计`2*(n-1)`步，对应着`2*(n-1)`个阶段，每个阶段都有向右或者向下2种决策，因此每个阶段都会对应一个状态集合。问题的目标在于找到一个状态序列，从而确定 `(0, 0)` 出发到 `(n-1, n-1)`的最短距离。因此整个问题是一个`多阶段决策最优解`问题。\n\n\n\n***这个问题是否满足`三大特征`呢？***\n\n对于任意一个节点`(i, j)`来说，从 `(0, 0)` 出发到 `(i, j)`存在多种路线，因此可能存在`重复子问题`。\n\n对于任意一个节点`(i, j)`来说，`(i, j)`这个位置的状态需要通过 `(i-1, j)`以及 `(i, j-1)`两个位置的状态来确定，但是并不需要关心这2个位置的状态的求解过程。而且，由于仅仅允许向右或者向下运动，因此前面阶段的状态确定了之后，不会被后面的状态所改变，因此满足`无后效性`的特征。\n\n定义状态为：`min_dist(i, j)`，表示从 `(0, 0)` 出发到 `(i, j)`的最短距离。那么到达`(i, j)`的最短路径必然经过`(i-1, j)`或 `(i, j-1)`，因此，到达`(i, j)`的最短路径必然包含到达这2个位置的最短路径之一。因此满足 `最优子结构` 的特征。\n\n综上所述，`min_dist(i, j) = w[i][j] + min(min_dist(i, j-1), min_dist(i-1, j))`。\n\n##### 求解:\n\n```java\n// 回溯算法\nprivate int min = Integer.MAX_VALUE;\npublic void minDist(int i, int j, int dist, int[][] w, int n) {\n    // terminator\n    if (i == n && j == n) {\n        if (dist < min) min = dist;\n        return;\n    }\n    // drill down\n    if (i < n) {\n        minDist(i + 1, j, dist + w[i][j], w, n);\n    }\n    if (j < n) {\n        minDist(i, j + 1, dist + w[i][j], w, n);\n    }\n}\n```\n\n```java\n// 递归+备忘录（缓存）减少重复计算\nprivate int[][] mem = new int[n][n];\npublic int minDist(int i, int j, int[][] w) {\n    if (i == 0 && j == 0) {\n        return w[0][0];\n    }\n    if (mem[i][j] > 0) {\n        return mem[i][j];\n    }\n    int minLeft = Integer.MAX_VALUE;\n    if (j-1>=0 ) {\n        minLeft = minDist(i, j-1);\n    }\n    int minUp = Integer.MAX_VALUE;\n    if (i-1>= 0) {\n        minUp = minDist(i-1, j);\n    }\n    int curMinDist = w[i][j] + Math.min(minLeft, minUp);\n    mem[i][j] = curMinDist;\n    return curMinDist;\n}\n```\n\n```java\n// 动态规划\npublic int minDist(int[][] w, int n) {\n    int[][] states = new int[n][n];\n    int sum = 0;\n    for (int j = 0; j < n; j++) {\n        sum += w[0][j];\n        states[0][j] = sum;\n    }\n    sum = 0;\n    for (int i = 0; i < n; i++) {\n        sum += w[i][0];\n        states[i][0] = sum;\n    }\n    for (int i = 1; i < n; i++) {\n        for (int j = 1; j < n; j++) {\n            states[i][j] = w[i][j] + Math.min(states[i][j-1], states[i-1][j]);\n        }\n    }\n    return states[n-1][n-1];\n}\n```\n\n\n\n### 一维动态规划：Fibnacci\n\n```java\n# 递归：自顶向下 O(2^N)\nint fib(int n) {\n    if (n <= 1) {\n        return n;\n    }\n    return fib(n - 1) + fib(n - 2); // 改进：return n <= 1 ? n : fib(n-1) + fib(n-2);\n}\n\n# 递归 + 备忘录 （记忆化搜索） O(N)\nint fib(int n, int[] memo) {\n    if (n <= 1) {\n        return n;\n    }\n    if (memo[n] == 0) {\n        memo[n] = fib(n-1, memo) + fib(n-2, memo);\n    }\n    return memo[n];\n}\n\n# 动态规划：自底向上 O(N)\nint fib(int n) {\n    int[] dp = new int[n];\n    dp[0] = 0;\n    dp[1] = 1;\n    for (int i = 2; i <= n; i++) {\n        dp[i] = dp[i-1] + dp[i-2];\n    }\n    return dp[n];\n}\n   \n# 一维的Equation: f(n) = f(n-1) + f(n-2)\n```\n\n\n\n### 二维动态规划：Count the paths\n\n```java\n// 递归\nint countPaths(boolean[][] grid, int row, int col) {\n    if (!validSqure(grid, row, col)) return 0;\n    if (isAtEnd(grid, row, col)) return 1;\n    return countPaths(grid, row + 1, col) + countPaths(grid, row, col+1);\n}\n\nopt[i, j] = opt[i+1, j] + opt[i, j+1];\nif a[i, j] == '空地'：\n    opt[i, j] = opt[i+1, j] + opt[i, j+1];\nelse: \n\topt[i, j] = 0;\n\n对比：\n# 一维的Equation: f(n) = f(n-1) + f(n-2)\n    \n# 二维的Equation: opt[i, j] = opt[i+1, j] + opt[i, j+1];\n```\n\n\n\n## 总结代码库（示例）\n\n* Valid anagram\n\n  ```python\n  # 思路：手动模拟hashtable，将字符串”a-z“的ASCII码作key，计数求差异    \n     def  isAnagram(self, s: str, t: str) -> bool:\n          arr1, arr2 = [0]*26, [0]*26\n          for i in s:\n              arr1[ord(i) - ord('a')] += 1\n          for i in t:\n              arr2[ord(i) - ord('a')] += 1\n          return arr1 == arr2\n  # 思路：map计数，对比计数差异\n      def isAnagram(self, s: str, t: str) -> bool:\n          dict1, dict2 = {}, {}\n          for item in s:\n              dict1[item] = dict1.get(item,0) + 1\n          for item in t:\n              dict2[item] = dict2.get(item,0) + 1\n          return dict1 == dict2\n  # 思路：数组排序后比较差异\n      def isAnagram(self, s: str, t: str) -> bool:\n          return sorted(s) == sorted(t)\n  ```\n\n  ```java\n  public class Solution {\n      public boolean isAnagram(String s, String t) {\n          if(s.length() != t.length()) return false;\n          int [] a = new int [26];\n          for(Character c : s.toCharArray()) a[c - 'a']++;\n          for(Character c : t.toCharArray()) {\n              if(a[c -'a'] == 0) return false;\n              a[c - 'a']--;\n          }\n          return true;\n      }\n      \n      public boolean isAnagram(String s1, String s2) {\n          int[] freq = new int[256];\n          for(int i = 0; i < s1.length(); i++) freq[s1.charAt(i)]++;\n          for(int i = 0; i < s2.length(); i++) if(--freq[s2.charAt(i)] < 0) return false;\n          return s1.length() == s2.length();\n      }\n      \n      \n  \tpublic boolean isAnagram(String s, String t) {\n      \tchar[] sChar = s.toCharArray();\n      \tchar[] tChar = t.toCharArray();\n      \tArrays.sort(sChar);\n      \tArrays.sort(tChar);\n      \treturn Arrays.equals(sChar, tChar);   \n  \t}\n  }\n  \n  ```\n\n*  Group Anagrams \n\n  ```python\n  def groupAnagrams(self, strs):\n      d = {}\n      for w in sorted(strs):\n          key = tuple(sorted(w))\n          d[key] = d.get(key, []) + [w]\n      return d.values()\n  \n  def groupAnagrams(self, strs):\n      dic = {}\n      for item in sorted(strs):\n          sortedItem = ''.join(sorted(item))\n          dic[sortedItem] = dic.get(sortedItem, []) + [item]\n      return dic.values()\n  ```\n\n  ```java\n  public List<List<String>> groupAnagrams(String[] strs) {\n  \tList<List<String>> res = new ArrayList<>();\n      HashMap<String, List<String>> map = new HashMap<>();\n      \n      Arrays.sort(strs);\n      for (int i = 0; i < strs.length; i++) {\n      \tString temp = strs[i];\n      \tchar[] ch = temp.toCharArray();\n      \tArrays.sort(ch);\n      \tif (map.containsKey(String.valueOf(ch))) {\n      \t\tmap.get(String.valueOf(ch)).add(strs[i]);\n      \t} else {\n      \t\tList<String> each = new ArrayList<>();\n      \t\teach.add(strs[i]);\n      \t\tmap.put(String.valueOf(ch), each);\n      \t}\n      }\n      for (List<String> item: map.values()) {\n      \tres.add(item);\n      }\n      return res;\n  }\n  ```\n\n*  Two sum \n\n  ```python\n  def twoSum(self, nums, target):\n      d = dict()\n      for index,num in enumerate(nums):\n          if d.get(num) == None:\n              d[target - num] = index\n          else:\n              return [d.get(num), index\n  ```\n\n  ```java\n  public int[] twoSum(int[] nums, int target) {\n      HashMap<Integer, Integer> tracker = new HashMap<Integer, Integer>();\n      int len = nums.length;\n      for (int i = 0; i < len; i++){\n          if (tracker.containsKey(nums[i])){\n              int left = tracker.get(nums[i]);\n              return new int[]{left+1, i+1};\n          } else {\n              tracker.put(target - nums[i], i);\n          }\n      }\n      return new int[2];\n  }\n  ```\n\n  \n\n\n\n## 刷题开始\n\n### Array\n\n#### 283. [move zeros]( https://leetcode-cn.com/problems/move-zeroes/ )\n\n> 方法1：将所有的非零元素都填充到数组前侧，然后将0填充到数组后侧  `#双指针法`\n\n```java\nclass Solution {\n    public void moveZeroes(int[] nums) {\n        int lastNotZeroIndex = 0;\n        for (int i = 0; i < nums.length; ++i) {\n            if (nums[i] != 0) {\n                nums[lastNotZeroIndex++] = nums[i];\n            }\n        }\n        \n        for (int i = lastNotZeroIndex; i < nums.length; ++i) {\n            nums[i] = 0;\n        }\n    }\n}\n```\n\n\n\n> 方法2：一维数组的坐标转换  i, j  `#双指针法`\n>\n> 用 j 记录上一个可能为0的值的索引，用 i 遍历数组，当遇到不为0的值的时候，将该元素 num[i] 与 nums[j] 交换，保证 j 前面的元素均为非0值。\n\n```java\nclass Solution {\n    public void moveZeroes(int[] nums) {\n        int lastZeroIndex = 0;\n        for (int i = 0; i < nums.length; ++i) {\n            if (nums[i] != 0) {\n                int temp = nums[i];\n                nums[i] = nums[lastZeroIndex];\n                nums[lastZeroIndex] = temp;\n                lastZeroIndex++;\n            }\n        }\n    }\n}\n```\n\n#### 11. [container with most water]( https://leetcode-cn.com/problems/container-with-most-water/ )\n\n> 思路：\n>\n> 1.`枚举`： left bar x, right bar y, (y - x) * min_height     O(n^2)    `#枚举`\n\n```java\n// 遍历数组的一个常见的办法:遍历左右边界，且左右边界不能重复\nclass Solution {\n    public int maxArea(int[] a) {\n        int max = 0\n        for (int i = 0; < a.length - 1; ++i) {\n            for (int j = i + 1; j < a.length; ++j) {\n                int area = (j - i) * Math.min(a[i], a[j]);\n                max = Math.max(max, area); \n            }\n        }\n        return max;\n    }\n}\n```\n\n> 2.`左右夹逼/双指针法`：左右边界 i, j, 向中间收敛                   `#双指针法：左右夹中间，中间到两边`\n\n```java\n// 遍历数组的一个常见的办法:遍历左右边界，且左右边界不能重复\nclass Solution {\n    public int maxArea(int[] a) {\n        int max = 0\n        for (int i = 0, j = a.length - 1; i < j; ) {\n            int minHeight = a[i] < a[j] ? a[i++] : a[j--];\n            max = Math.max(max, (j - i + 1) * minHeight); \n        }\n        return max;\n    }\n}\n```\n\n#### 70. [climbing stairs](https://leetcode-cn.com/problems/climbing-stairs/)\n\n```java\nclass Solution {\n    public int climbStairs(int n) {\n        if (n <= 2) return n;\n        int f1 = 1;\n        int f2 = 2;\n        int f3 = 3;\n        for (int i = 3; i <= n; i++) {\n            f3 = f1 + f2;\n            f1 = f2;\n            f2 = f1;\n        }\n        return f3;\n    }\n}\n```\n\n#### 1. [2sum](https://leetcode-cn.com/problems/two-sum/)\n\n> 方法1：暴力解法 O(n^2)\n\n```java\n// 遍历数组的一个常见的办法:遍历左右边界，且左右边界不能重复\nclass Solution {\n    public int[] twoSum(int[] nums, int target) {\n        for (int i = 0; i < nums.length - 1; ++i) {\n            for (int j = i + 1; j < nums.length; ++j) {\n                if (nums[i] + nums[j] == target) {\n\t\t\t\t\treturn new int[] {i, j};\n                }\n            }\n        }\n        return new int[2];\n    }\n}\n```\n\n> 方法2：两遍哈希表  \n>\n> 思想：空间换时间\n>\n> ***保持数组中的每个元素与其索引相互对应的最好方式是什么？ 哈希表。***\n>\n> 哈希表查找的时间复杂度为 O(1)。\n\n```java\nclass Solution {\n    public int[] twoSum(int[] nums, int target) {\n        Map<Integer, Integer> map = new HashMap<>();\n        for (int i = 0; i < nums.length; ++i) {\n            map.put(target - nums[i], i);\n        }\n        for (int i = 0; i < nums.length; ++i) {\n            if (map.containsKey(nums[i]) && i != map.get(nums[i])) {\n                return new int[] {i, map.get(nums[i])};\n            }\n        }\n        return new int[2];\n    } \n}\n```\n\n> 方法3：一遍哈希表\n>\n> 由于在遍历数组的过程中，可以回过头来查找哈希表中是否存储了目标元素的值，因此，没有必要遍历完整的数组将目标元素的值存储到哈希表中，可以边遍历边存储。\n\n```java\nclass Solution {\n    public int[] twoSum(int[] nums, int target) {\n        Map<Integer, Integer> map = new HashMap<>();\n        for (int i = 0; i < nums.length; ++i) {\n            int component = target - nums[i];\n            if (map.containsKey(component)) {\n                return new int[] {map.get(component), i};\n            }\n            map.put(nums[i], i);\n        }\n        return new int[2];\n    } \n}\n```\n\n\n\n#### 15. [3sum](https://leetcode-cn.com/problems/3sum/)\n\n> 思路：转化 a + b = -c\n>\n> 1.暴力解法：三重循环\n>\n> 2.HashMap\n>\n> 3.`左右夹逼/双指针法`，这种办法有时候需要排序。\n\n### Linked List\n\n#### 141.  [linked-list-cycle](https://leetcode.com/problems/linked-list-cycle) \n\n> 1.暴力解法：遍历链表，hash/set\n>\n> 2.`快慢指针 `                                                                            `#快慢指针法`\n\n\n\n### Stack\n\n#### 20. [valid parentheses](https://leetcode-cn.com/problems/valid-parentheses/description/)\n\n> 为啥这个题目可以用栈解决？ 具有最近相关性\n>\n> 1.暴力解法：不断replace匹配的括号 -> \"\" O(n^2)\n>\n> a. (){}[]\n>\n> b.((({[]})))\n>\n> 2.Stack\n\n#### 155. [min Stack](https://leetcode-cn.com/problems/min-stack/)\n\n> `两个队列实现栈`\n>\n> `两个栈实现队列`\n\n#### 84. [largest rectangle in histogram](https://leetcode-cn.com/problems/largest-rectangle-in-histogram/)\n\n> 思考一下这个题目和 [container with most water]( https://leetcode-cn.com/problems/container-with-most-water/ ) 有何差别？\n>\n> 差别在于这个题目的高度是指所有柱子中最低的高度，而 [container with most water]( https://leetcode-cn.com/problems/container-with-most-water/ ) 则是左右两边最小的高度。\n>\n> 1.暴力解法 O(n^3)\n>\n> ```java\n> for i -> 0, n-2\n>     for j -> i+1, n-1\n>         (i, j) -> 最小高度， area\n>         update max-area\n> ```\n>\n> 2.`暴力加速`\n>\n> ```java\n> for i -> 0, n-1\n>     找到 left bound, right bound   // 固定中间一个高度，找到左右两边比他小的最小值\n>     area = height[i] * (right - left)\n>     update max-area\n> ```\n>\n> 3.`Stack：有序栈(单调栈)找左右边界`   `#单调栈`\n>\n> 维护一个从小到大的有序栈\n>\n> 那么左边界left bound在栈里，而右边界则是比栈顶元素小的新元素\n>\n> 如果新元素的值大于栈顶元素，说明栈顶元素的右边界没有找到。\n>\n> 构造这个有序栈的过程，其实就是不断找到栈顶元素的右边界的过程（左边界在栈里）。\n\n### Queue\n\n#### 239. [sliding window maximum](https://leetcode-cn.com/problems/sliding-window-maximum/)\n\n> 1.暴力 O(n*k)\n>\n> 2.`deque O(n)` 滑动窗口 -> 队列        `#单调队列`\n\n### Hash Table\n\n#### [242. valid anagram](https://leetcode-cn.com/problems/valid-anagram/description/)  \n\n> `#切题四件套`\n>\n> clarification\n>\n> -确定异位词是什么意思？\n>\n> -确定大小写是否敏感？\n>\n> 方法1：\n>\n> 暴力 sort -> sorted_str 是否相等？ O(NlogN)\n>\n> 方法2：哈希表 \n>\n> 统计每个字符出现的频次\n>\n> （1）第一个string，碰到字母加1，第二个string，碰到同样的字母减1，最后看map是否为空\n>\n> （2）int[256] 的数组，ascii -> index\n\n#### [49.group anagrams](https://leetcode-cn.com/problems/group-anagrams/)\n\n### Tree\n\n#### [94. binary tree inorder traversal](https://leetcode-cn.com/problems/binary-tree-inorder-traversal/)\n\n#### [98. validate binary search tree](https://leetcode-cn.com/problems/validate-binary-search-tree/)\n\n> 中序遍历是递增的。\n\n### Recursion\n\n#### [70. climbing stairs](https://leetcode-cn.com/problems/climbing-stairs/)\n\n> 找 `最近重复性`\n>\n> 1: 1\n>\n> 2: 2\n>\n> 3: f(1) + f(2) 1的总的走法，跨2步走上3 + 2的总的走法，跨1步走上3 mutual exclusive, complete exhaustive\n>\n> 4: f(2) + f(3)\n>\n> ...\n>\n> n: f(n) = f(n-1) + f(n-2)  Fibonacci\n\n```java\nclass Solution {\n    public int climbStairs(int n) {\n        if(n <= 2) return n;\n        return climbStairs(n-1) + climbStairs(n-2);\n    }\n}\n```\n\n#### [22. generate parenthess * ](https://leetcode-cn.com/problems/generate-parentheses/)\n\n```java\n// 递归模板\nclass Solution {\n    public void generateParenthesis(int n) {\n        generate(0, 2 * n, \"\");\n    }\n    \n    private void generate(int level, int max, String s) {\n        // terminator\n        if (level >= max) {\n            System.out.println(s);\n            return; \n        }\n        // process current logic\n        String s1 = s + \"(\";\n        String s2 = s + \")\";\n        // drill down\n        generate(level + 1, max, s1);\n        generate(level + 1, max, s2);\n        // reverse states\n    }\n}\n\n// 检查括号合法性\n// left 随时加，只要不超标 n\n// right 左括号个数 > 右括号个数\nclass Solution {\n    List<String> result;\n    \n    public List<String> generateParenthesis(int n) {\n        result = new ArrayList<>();\n        generate(0, 0, n, \"\");\n    }\n    \n    private void generate(int left, int right, int n, String s) {\n        // terminator\n        if (left == n && right == n) {\n            result.add(s);\n            return; \n        }\n        // process current logic\n        String s1 = s + \"(\";\n        String s2 = s + \")\";\n        // drill down\n        if (left < n) {\n            generate(left + 1, right, n, s1);\n        }\n        if (left > right) {\n            generate(left, right + 1, n, s2);\n        }\n        generate(level + 1, max, s1);\n        generate(level + 1, max, s2);\n        // reverse states\n    }\n}\n// 本质就是DFS\n```\n\n### Divide and conquer\n\n#### [50. Pow(x, n)](https://leetcode-cn.com/problems/powx-n/)\n\n> 1.暴力 O(n)\n>\n> ```java\n> result = 1;\n> for (int i = 0; i < n; i++) {\n>     result *= x;\n> }\n> ```\n>\n> 2.分治 O(logn)\n>\n> `template`: 1. terminator 2. process (`divide` your big problem) 3. drill down (`conquer` your subproblems ) 4. `merge` sub result 5. reverse states. \n>\n> ```java\n> pow(x, n):\n> \tsubproblem: subresult = pow(x, n/2);\n> \tmege:\n> \t\tif (n % 2 == 1) {\n>         \tresult = subresult * subresult * x;\n>         } else {\n>             result = subresult * subresult;\n>         } \n> ```\n\n#### [78. subsets](https://leetcode-cn.com/problems/subsets/) * \n\n```java\npublic List<List<Integer>> subsets(int[] nums) {\n    List<List<Integer>> ans = new ArrayList<>();\n    if (nums == null) return ans;\n    dfs(ans, nums, new ArrayList<Integer>(), 0);\n    return ans;\n}\n\nprivate void dfs(List<List<Integer>> ans, int[] nums, List<Integer> list, int index) {\n    // terminator\n    if (index == nums.length) {\n        ans.add(new ArrayList<Integer>(list));\n        return;\n    }\n    \n    // not pick the number at this index\n    dfs(ans, nums, list, index + 1);\n    \n    // pick the number at this index\n    list.add(num[index]);\n    dfs(ans, nums, list, index + 1);\n    \n    // reverse the current state\n    list.remove(list.size() - 1);\n}\n\n// or\nprivate void dfs(List<List<Integer>> ans, int[] nums, List<Integer> list, int index) {\n    // terminator\n    if (index == nums.length) {\n        ans.add(new ArrayList<Integer>(list));\n        return;\n    }\n    \n    // not pick the number at this index\n    dfs(ans, nums, list.clone, index + 1);\n    \n    // pick the number at this index\n    list.add(num[index]);\n    dfs(ans, nums, list.clone, index + 1);\n    \n    // reverse the current state\n}\n```\n\n```python\nclass Solution(object):\n    def subsets(self, nums):\n        result =[[]]\n        for num in nums:\n            newsets = []\n            for subset in result:\n                new_subset = subset + [num]\n                newsets.append(new_subset)\n           \tresult.extend(newsets) \n       \treturn result\n```\n\n#### [169. majority element](https://leetcode-cn.com/problems/majority-element/description/)\n\n#### [17. letter combinations of a phone number](https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number/) * \n\n```java\npublic List<String> letterCombination(String digits) {\n    if (digits == null || digits.length() == 0) {\n        return new ArrayList();\n    }\n    Map<Character, String> map = new HashMap<>();\n    map.put('2', \"abc\");\n    map.put('3', \"def\");\n \tmap.put('4', \"ghi\");\n    map.put('5', \"jkl\");\n    map.put('6', \"mno\");\n    map.put('7', \"pqrs\");\n    map.put('8', \"tuv\");\n    map.put('9', \"wxyz\");   \n    List<String> res = new ArrayList<>();\n    search(\"\", digits, 0, res, map);\n    return res;\n}\n\nprivate void search(String s, \n                    String digits, \n                    int i, // level\n                   List<String> res,\n                   Map<Character, String> map) {\n\t// terminator\n    if (i == digits.length) {\n        res.add(s);\n        return;\n    }\n    // process\n    String letters = map.get(digits.charAt(i));\n    for (int j = 0;  j < letters.length(); j++) {\n        // drill down\n        search(s+letters.charAt(j), digits, i+1, res, map);\n    }\n}\n```\n\n#### [51. n queens](https://leetcode-cn.com/problems/n-queens/)\n\n```python\ndef sovleNQueen(self, n):\n    if n < 1: return []\n    self.result = []\n    \n    # 之前的皇后所攻击的位置(列，pie, na)\n    self.cols = set();\n    self.pie = set();\n    self.na = set();\n    \n    self.DFS(n, 0, [])\n    return self._generate_result(n)\n\ndef DFS(self, n, row, cur_state):\n    # ternimator\n    if row >= n:\n        self.result.append(cur_state)\n        return \n    \n    # current level! Do it!\n    for col in range(n):  # 遍历列 column\n        if col in self.cols or row + col in self.pie or row - col in self.na:\n            # go die\n            continue\n   \t\t\n        # update the flags\n        self.cols.add(col)\n        self.pie.add(row+col)\n        self.na.add(row-col)\n        \n        self.DFS(n, row + 1, cur_state + [col])\n        \n        # reverse state\n        self.cols.remove(col)\n        self.pie.remove(row+col)\n        self.na.remove(row-col)\n       \ndef _generate_result(self, n):\n    board = []\n    for res in self.result:\n        for i in res:\n            board.append(\".\" * i + \"Q\"  + \".\" * (n - i - 1))\n    return [board[i: i + n] for i in range(0, len(board), n)]\n        \n```\n\n\n\n### Binary Search\n\n#### [69. sqrtx](https://leetcode-cn.com/problems/sqrtx/)\n\n```java\nclass Solution {\n    public int mySqrt(int x) {\n        if (x == 0 || x == 1) {\n            return x;\n        }\n        long left = 1;\n        long right = x / 2; // (x/2)^2 >= x\n        while (left < right) {\n            long mid = left + (right - left + 1) / 2;\n            if (mid * mid > x) {\n                right = mid - 1;\n            } else {\n                left = mid;\n            }\n        }\n        return (int)left;\n    }\n}\n```\n\n* 扩展阅读：[牛顿迭代法](https://www.beyond3d.com/content/articles/8/)\n\n#### [33. search in rotated sorted array](https://leetcode-cn.com/problems/search-in-rotated-sorted-array/)\n\n> 1.暴力遍历 O(N)\n>\n> 2.还原O(log N) -> 升序 -> 二分查找O(log N)\n>\n> 3.二分查找O(log N)\n\n```java\nclass Solution {\n    public int search(int[] nums, int target) {\n        int left = 0;\n        int right = nums.length - 1;\n        \n        while (left < right) {\n            int mid = left + (right - left) / 2;\n            if (nums[0] <= nums[mid] && (target > nums[mid] || target < nums[0])) {\n                left = mid + 1;\n            } else if (target > nums[mid] && target < nums[0]) {\n                left = mid + 1;\n            } else {\n                right = mid;\n            }\n        }\n        return left == right && nums[left] == target ? left : -1;\n    }\n}\n```\n\n\n\n### BFS & DFS\n\n#### [102. binary tree level order traversal](https://leetcode-cn.com/problems/binary-tree-level-order-traversal/#/description)\n\n> 1.BFS\n>\n> 2.DFS\n\n#### [22. generate parenthess * ](https://leetcode-cn.com/problems/generate-parentheses/)\n\n> DFS\n\n#### [200. number of islands](https://leetcode-cn.com/problems/number-of-islands/)\n\n> floodfill\n\n```java\nclass Solution {\n    int[] dx = new int[]{-1, 1, 0, 0};\n    int[] dy = new int[]{0, 0, -1, 1};\n    char[][] g;\n    \n    public int numIslands(char[][] grid) {\n    \tint islands = 0;\n        g = grid;\n        for (int i = 0;  i < g.length; i++) {\n            for (int j = 0; j < g[i].length; j++) {\n                if (g[i][j] == '0') continue;\n                islands += sink(i, j);\n            }\n        }\n        return islands;\n    }\n    \n    private int sink(int i, int j) {\n        if (g[i][j] == '0') {\n            return 0;\n        }\n        \n        g[i][j] = '0';\n        \n        for (int k = 0; k < dx.length; k++) {\n            int x = i + dx[k];\n            int y = j + dy[k];\n            if (x >= 0 && x < g.length && y >= 0 && y < g[x].length) {\n                if (g[x][y] == '0') continue;\n                sink(x, y);\n            }\n        }\n        \n        return 1;\n    }\n}\n```\n\n#### [79. word search](https://leetcode-cn.com/problems/word-search/) 与212一起看\n\n### Greedy\n\n> 从后往前\n>\n> 从前往后\n>\n> 从某个点切入往某一边\n\n#### [455. assign cookies]( https://leetcode-cn.com/problems/assign-cookies/ )\n\n#### [122. best time to buy and sell stock ii](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/description/)\n\n#### [55. jump game](https://leetcode-cn.com/problems/jump-game/)\n\n```java\nclass Solution {\n    public boolean canJump(int[] nums) {\n        if (nums == null) {\n            return false;\n        }\n        \n        int endReachable = nums.length - 1;\n        for (int i = nums.length - 1; i >= 0; i--) {\n            if (nums[i] + i >= endReachable) {\n                endReachable = i;\n            }\n        }\n        \n        return endReachable == 0;\n    }\n}\n```\n\n\n\n### Dynamic Programming\n\n\n\n#### [70. climbing stairs](https://leetcode-cn.com/problems/climbing-stairs/)\n\n> 找 `最近重复性`\n>\n> 1: 1\n>\n> 2: 2\n>\n> 3: f(1) + f(2) 1的总的走法，跨2步走上3 + 2的总的走法，跨1步走上3 mutual exclusive, complete exhaustive\n>\n> 4: f(2) + f(3)\n>\n> ...\n>\n> n: f(n) = f(n-1) + f(n-2)  Fibonacci\n>\n\n```java\nclass Solution {\n    public int climbStairs(int n) {\n        if(n <= 2) return n;\n        return climbStairs(n-1) + climbStairs(n-2);\n    }\n}\n\nclass Solution {\n    public int climbStairs(int n) {\n        if (n <= 2) return n;\n        int f1 = 1;\n        int f2 = 2;\n        int f3 = 3;\n        for (int i = 3; i <= n; i++) {\n            f3 = f1 + f2;\n            f1 = f2;\n            f2 = f1;\n        }\n        return f3;\n    }\n}\n\nclass Solution {\n    public int climbStairs(int n) {\n        if (n <= 2) return n;\n        int[] dp = new int[n];\n        \n        dp[0] = 1;\n        dp[1] = 2;\n        for (int i = 2; i < n; i++) {\n        \tdp[i] = dp[i-1] + dp[i-2];\n    \t}\n    \treturn dp[n-1];\n\t}\n}\n```\n\n\n\n> 进阶：\n>\n> （1）可以走1,  2，3步，如何解决？easy    ->   f(n) = f(n-1) + f(n-2) + f(n-3)\n>\n> （2）给定一个数组[x1, x2, ..., xn ] 表示可以走 x1，x2, ..., xn步， 如何解决？\n>\n> （2）相邻2步的步伐不同，如何解决？ medium\n\n\n\n##### 小结：一维动态规划：Fibnacci\n\n```java\n# 递归：自顶向下 O(2^N)\nint fib(int n) {\n    if (n <= 1) {\n        return n;\n    }\n    return fib(n - 1) + fib(n - 2); // 改进：return n <= 1 ? n : fib(n-1) + fib(n-2);\n}\n\n# 递归 + 备忘录 （记忆化搜索） O(N)\nint fib(int n, int[] memo) {\n    if (n <= 1) {\n        return n;\n    }\n    if (memo[n] == 0) {\n        memo[n] = fib(n-1, memo) + fib(n-2, memo);\n    }\n    return memo[n];\n}\n\n# 动态规划：自底向上 O(N)\nint fib(int n) {\n    int[] dp = new int[n+1];\n    dp[0] = 0;\n    dp[1] = 1;\n    for (int i = 2; i <= n; i++) {\n        dp[i] = dp[i-1] + dp[i-2];\n    }\n    return dp[n];\n}\n   \n# 一维的Equation: f(n) = f(n-1) + f(n-2)\n```\n\n\n\n#### [62. unique paths](https://leetcode-cn.com/problems/unique-paths/)\n\n> ```\n> opt[i, j] = opt[i+1, j] + opt[i, j+1];\n> if a[i, j] == '空地'：\n>     opt[i, j] = opt[i+1, j] + opt[i, j+1];\n> else: \n> \topt[i, j] = 0;\n> ```\n\n```java\nint countPaths(boolean[][] grid, int row, int col) {\n    if (!validSqure(grid, row, col)) return 0;\n    if (isAtEnd(grid, row, col)) return 1;\n    return countPaths(grid, row + 1, col) + countPaths(grid, row, col+1);\n} \n\nclass Solution {\n    // 二维DP数组\n    public int uniquePaths(int m, int n) {\n        int[][] dp = new int[m][n];\n        for (int i = 0; i < m; i++) {\n            dp[i][0] = 1;\n        }\n        for (int j = 0; j < n; j++) {\n            dp[0][j] = 1;\n        }\n        for (int i = 1; i < m; i++) {\n            for (int j = 1; j < n; j++) {\n                dp[i][j] = dp[i-1][j] + dp[i][j-1];\n            }\n        }\n        return dp[m-1][n-1];\n    }\n    \n    // 一维DP数组：将每一行都压缩在固定的一行更新，更新m次\n    public int uniquePaths(int m, int n) {\n        int[] dp = new int[n];\n        Arrays.fill(dp, 1);\n        for (int i = 1; i < m; i++) {\n            for (int j = 1; j < n; j++) {\n                dp[j] += dp[j-1];\n            }\n        }\n        return dp[n-1];\n    }\n}\n```\n\n#### [65. unique paths ii](https://leetcode-cn.com/problems/unique-paths-ii/submissions/)\n\n```java\nclass Solution {\n    public int uniquePathsWithObstacles(int[][] obstacleGrid) {\n        int n = obstacleGrid[0].length;\n        int[] dp = new int[n];\n        dp[0] = 1;\n        for (int[] row : obstacleGrid) {  // 注意这种写法\n            for (int j = 0; j < n; j++) {  // 这里j一定要从0开始，因为row[0]可能是障碍物\n                if (row[j] == 1) {\n                    dp[j] = 0;\n                } else if (j > 0){\n                    dp[j] += dp[j-1];\n                }\n            }\n        }\n        return dp[n-1];\n    }\n}\n```\n\n\n#### [64. minimum path sum](https://leetcode-cn.com/problems/minimum-path-sum/submissions/)\n\n```java\n// 暴力解法\nclass Solution {\n    public int minPathSum(int[][] grid) {\n        return minPathSum(0, 0, grid);\n    }\n\n    private int minPathSum(int i, int j, int[][] grid) {\n        if (i == grid.length || j == grid[0].length) return Integer.MAX_VALUE;\n        if (i == grid.length - 1 && j == grid[0].length - 1) {\n            return grid[i][j];\n        }\n        return grid[i][j] + Math.min(minPathSum(i+1, j, grid), minPathSum(i, j+1, grid));\n    }\n}\n\n// 动态规划\nclass Solution {\n    public int minPathSum(int[][] grid) {\n        if (grid == null || grid.length <= 0 || grid[0].length <= 0) {\n            return 0;\n        }\n        int m = grid.length;\n        int n = grid[0].length;\n        int[][] states = new int[m][n];\n        int sum = 0;\n        for (int j = 0; j < n; j++) {\n            sum += grid[0][j];\n            states[0][j] = sum;\n        }\n        sum = 0;\n        for (int i = 0;  i < m; i++) {\n            sum += grid[i][0];\n            states[i][0] = sum;\n        }\n        for (int i = 1; i < m; i++) {\n            for (int j = 1; j < n; j++) {\n                states[i][j] = grid[i][j] + Math.min(states[i][j-1], states[i-1][j]);\n            }\n        }\n        return states[m-1][n-1];\n    }\n}\n```\n\n##### 小结：二维动态规划：Count the paths\n\n```java\n// 递归\nint countPaths(boolean[][] grid, int row, int col) {\n    if (!validSqure(grid, row, col)) return 0;\n    if (isAtEnd(grid, row, col)) return 1;\n    return countPaths(grid, row + 1, col) + countPaths(grid, row, col+1);\n}\n\nopt[i, j] = opt[i+1, j] + opt[i, j+1];\nif a[i, j] == '空地'：\n    opt[i, j] = opt[i+1, j] + opt[i, j+1];\nelse: \n\topt[i, j] = 0;\n\n对比：\n# 一维的Equation: f(n) = f(n-1) + f(n-2)\n    \n# 二维的Equation: opt[i, j] = opt[i+1, j] + opt[i, j+1];\n```\n\n#### [120. triangle](https://leetcode-cn.com/problems/triangle/description/) ([一个不错的分析过程](https://leetcode.com/problems/triangle/discuss/38735/Python-easy-to-understand-solutions-(top-down-bottom-up).))\n\n> 1、brute-force 递归， n层： left or right: O(2^N)\n>\n> 2、DP\n>\n> a.  重复性 `problem(i, j) = min(sub(i+1, j) , sub(i+1, j+1)) + a[i][j]`\n>\n> b. 状态数组 `f(i, j) `\n>\n> c. DP方程 `f(i, j) = min(f(i+1, j) , f(i+1, j+1)) + a[i][j]`\n>\n\n```python\nclass Solution:\n    def minimumTotal(self, triangle):\n        \"\"\"\n        :type triangle: List[List[int]]\n        :rtype: int\n        \"\"\"\n        dp = triangle\n        for i in range(len(triangle) - 2, -1, -1):\n            for j in range(len(triangle[i])):\n                dp[i][j] += min(dp[i+1][j], dp[i+1][j+1])\n        print(triangle[0][0])\n        return dp[0][0]\n```\n\n```java\nclass Solution {\n    public int minimumTotal(List<List<Integer>> triangle) {\n        int[] dp = new int[triangle.size() + 1];\n        for (int i = triangle.size() - 1; i >= 0; i--) {\n            for (int j = 0; j < triangle.get(i).size(); j++) {\n                dp[j] = Math.min(dp[j], dp[j+1]) + triangle.get(i).get(j);\n            }\n        }\n        return dp[0];\n    }\n}\n```\n\n```java\nclass Solution {\n    int maxRow;\n    public int minimumTotal(List<List<Integer>> triangle) {\n\t\tmaxRow = triange.size();\n        return helper(0, 0, triangle);\n    }\n    \n    private int helper(int row, int col, List<List<Integer>> triangle) {\n        if (row == maxRow-1) {\n            return triangle.get(row).get(col);\n        }\n        int left = helper(row+1, col, triangle);\n        int right = helper(row+1, col+1, triangle);\n        return Math.min(left, right) + triangle.get(row).get(col);\n    }\n}\n```\n\n```java\nclass Solution {\n    int maxRow;\n    Integer[][] memo;\n    public int minimumTotal(List<List<Integer>> triangle) {\n\t\tmaxRow = triange.size();\n        memo = new Integer[row][row];\n        return helper(0, 0, triangle);\n    }\n    \n    private int helper(int row, int col, List<List<Integer>> triangle) {\n        if (memo[row][col] != null) {\n            return memo[row][col];\n        }\n        if (row == maxRow-1) {\n            return memo[row][col] = triangle.get(row).get(col);\n        }\n        int left = helper(row+1, col, triangle);\n        int right = helper(row+1, col+1, triangle);\n        return memo[row][col] = Math.min(left, right) + triangle.get(row).get(col);\n    }\n}\n```\n\n\n\n#### [53. maximum sum subarray](https://leetcode-cn.com/problems/maximum-subarray/)\n\n> 1、暴力 O(N^2)\n>\n> 2、DP\n>\n> a. 重复性 max_sum(i) = Max(max_sum(i-1) , 0) + a[i]  max_sum(i) : 表示以第i个元素结尾（包含）的连续子数组最大和\n>\n> b. 状态数组 f(i)  \n>\n> c. DP方程 f(i) = max(f(i-1), 0) + a[i]\n\n```python\nclass Solution(object):\n    def maxSubArray(self, nums):\n        \"\"\"\n        1. dp[i] = max(nums[i], nums[i] + dp[i-1])\n        2. 最大子序列和 = 当前元素最大（之前元素和为负） 或者 包含之前+当前之后最大\n        \"\"\"\n        dp = nums\n        for i in range(1, len(nums)):\n            dp[i] = max(0, dp[i-1]) + nums[i]\n        return max(dp) \n```\n\n\n\n#### [152. maximum product subarray](https://leetcode-cn.com/problems/maximum-product-subarray/description/)\n\n\n\n#### [322. coin change]( https://leetcode-cn.com/problems/coin-change/description/ ) ([推荐题解](https://leetcode-cn.com/problems/coin-change/solution/ling-qian-dui-huan-by-leetcode/))\n\n> 1、暴力递归\n>\n> 2、BFS\n>\n> 3、DP\n>\n> a. 重复性\n>\n> b. DP array\n>\n> c. DP equation:  f(n) = min{f(n-k), for k in [1, 2, 5]} + 1\n>\n> \n>\n> 变形：若问`共有多少种组合方式`?\n>\n> 分析：这个问题就类似于爬楼梯问题，爬楼梯每次可以爬1阶，每次可以爬2阶，每次也可以爬5阶，问爬到11阶有多少种方式？（不同之处在于硬币[1,2,1]和[1,1,2]是一种情况，而爬楼梯则不是）\n\n```java\npublic class Solution {\n    public int coinChange(int[] coins, int amount) {\n        return coinChange(0, coins, amount);\n    }\n    \n    private int coinChange(int index, int[] coins, int amount) {\n        if (amount == 0) {\n            return 0;\n        }\n        if (index < coins.length && amount > 0) {\n            int maxVal = amount / coins[index];\n            int minCost = Integer.MAX_VALUE;\n            for (int x = 0; x <= maxVal; x++) {\n                if (amount >= x * coins[index]) {\n                    int res = coinChange(index+1, coins, amount - x * coins[index]);\n                    if (res != -1) {\n                        minCost = Math.min(minCost, res + x);\n                    }\n                }\n            }\n            return minCost == Integer.MAX_VALUE ? -1 : minCost;\n        }\n        return -1;\n    }\n}\n```\n\n```java\npublic class Solution {\n    public int coinChange(int[] coins, int amount) {\n        if (amount <=0) return 0;\n        return coinChange(coins, amount, new int[amount]);\n    }\n    \n    private int coinChange(int[] coins, int remain, int[] count) {\n        if (remain < 0) {\n            return -1;\n        }\n        if (remain == 0) {\n            return 0;\n        }\n        if (count[remain-1] != 0) {\n            return count[remain-1];\n        }\n        int min = Integer.MAX_VALUE;\n        for (int coin : coins) {\n            int res = coinChange(coins, remain - coin, count);\n            if (res >= 0 && res < min) {\n                min = res + 1;\n            }\n        }\n        count[remain - 1] = min == Integer.MAX_VALUE ? -1 : min;\n        return count[remain - 1];\n    }\n}\n```\n\n```java\nclass Solution {\n    public int coinChange(int[] coins, int amount) {\n        int max = amount + 1;\n        int[] dp = new int[amount + 1];\n        Arrays.fill(dp, max);\n        dp[0] = 0;\n        for (int i = 1; i <= amount; i++) {\n            for (int j = 0; j < coins.length; j++) {\n                if (coins[j] <= i) {\n                \tdp[i] = Math.min(dp[i], dp[i-coins[j]] + 1);\n                }\n            }\n        }\n        return dp[amount] > amount ? -1 : dp[amount];\n    }\n}\n```\n\n\n\n#### [1143. longest common subsequence](https://leetcode-cn.com/problems/longest-common-subsequence/)\n\n> `# 经验` \n>\n> 1.对于2个字符串的比较，很多时候，我们会从字符串的尾部向前看。\n>\n> 2.对于2个字符串的变化问题，很多时候会表示成一个二维数组，行和列的元素分别是2个字符串的字符\n\n```java\nclass Solution {\n    public int longestCommonSubsequence(String text1, String text2) {\n        if (text1 == null || text2 == null) {\n            return 0;\n        }\n        int n = text1.length();\n        int m = text2.length();\n        int[][] dp = new int[n+1][m+1];\n        for (int i = 1; i <= n; i++) {\n            for (int j = 1; j <= m; j++) {\n                if (text1.charAt(i-1) == text2.charAt(j-1)) {\n                    dp[i][j] = dp[i-1][j-1] + 1;\n                } else {\n                    dp[i][j] = Math.max(dp[i-1][j], dp[i][j-1]);\n                }\n            }\n        }\n        return dp[n][m];\n    }\n    \n    public int longestCommonSubsequence(String text1, String text2) {\n        if (text1 == null || text2 == null) {\n            return 0;\n        }\n        int n = text1.length();\n        int m = text2.length();\n        int[] dp = new int[m+1];\n        for (int i = 1; i <= n; i++) {\n            int temp = 0;  \n            for (int j = 1; j <= m; j++) {\n                int prev = temp;\n                temp = dp[j];\n                if (text1.charAt(i-1) == text2.charAt(j-1)) {\n                    dp[j] = prev + 1;\n                } else {\n                    dp[j] = Math.max(dp[j], dp[j-1]) ;\n                }\n            }\n        }\n        return dp[m];\n    }\n}\n```\n\n\n\n#### [72. edit distance (莱文斯坦距离)](https://leetcode-cn.com/problems/edit-distance/)\n\n> 1、BFS,  two-ended BFS\n>\n> 2、DP\n>\n> `dp[i][j] // word1.substr(0, i) 与 word2.substr(0, j)的编辑距离`\n>\n> (1) if w1[i] == w2[j]\n>\n> w1:  ............x (i)\n>\n> w2: .............x (j)\n>\n> edit_dist(i, j) = edit_dist(i-1, j-1) \n>\n> (2) if w1[i] != w2[j]\n>\n> w1:  ............x (i)\n>\n> w2: .............y (j)\n>\n> edit_dist(i, j) =  \n>\n> min(\n>\n> ​\t\t\tedit_dist(i-1, j-1) + 1    // x -> y (w1) or y -> x (w2)    \n>\n> ​\t\t\tedit_dist(i - 1, j) + 1     // 删除 x\n>\n> ​\t\t\tedit_dist(i, j - 1) + 1     // 删除 y \n>\n> )\n\n```java\nclass Solution {\n    // 单独处理空字符串的dp\n    public int minDistance(String word1, String word2) {\n        if (word1 == null || word2 == null) {\n            return 0;\n        }\n        int n = word1.length();\n        int m = word2.length();\n        if (n == 0) {\n            return m;\n        } else if (m == 0) {\n            return n;\n        }\n        int[][] dp = new int[n][m];\n        for (int j = 0; j < m; j++) {\n            if (word1.charAt(0) == word2.charAt(j)) dp[0][j] = j;\n            else if (j != 0) dp[0][j] = dp[0][j-1] + 1;\n            else dp[0][j] = 1;\n        }\n        for (int i = 0; i < n; i++) {\n            if (word1.charAt(i) == word2.charAt(0)) dp[i][0] = i;\n            else if (i != 0) dp[i][0] = dp[i-1][0] + 1;\n            else dp[i][0] = 1;\n        }\n        for (int i = 1; i < n; i++) {\n            for (int j = 1; j < m; j++) {\n                if (word1.charAt(i) == word2.charAt(j)) {\n                    dp[i][j] = min(dp[i-1][j] + 1, dp[i][j-1] + 1, dp[i-1][j-1]);\n                } else {\n                    dp[i][j] = min( dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + 1;\n                }\n            }\n        }\n        return dp[n-1][m-1];\n    }\n    // 统一处理空字符串的dp\n    public int minDistance(String word1, String word2) {\n        int n = word1.length();\n        int m = word2.length();\n        int[][] dp = new int[n+1][m+1];\n        for (int j = 0; j <= m; j++) {\n            dp[0][j] = j;\n        }\n        for (int i = 0; i <= n; i++) {\n            dp[i][0] = i;\n        }\n        for (int i = 1; i <= n; i++) {\n            for (int j = 1; j <= m; j++) {\n                if (word1.charAt(i-1) == word2.charAt(j-1)) {\n                    dp[i][j] = dp[i-1][j-1];\n                } else {\n                    dp[i][j] = min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + 1;\n                }\n            }\n        }\n        return dp[n][m];\n    }\n\n    private int min(int x, int y, int z) {\n        return Math.min(x, Math.min(y, z));\n    }   \n}\n```\n\n#### [198. house robber](https://leetcode-cn.com/problems/house-robber/)\n\n>  `a[i] `: 0...i 能偷到的 max value : a[n-1]\n>\n> `a[i][0,1]`:  0： 表示第 i 个房子不偷，1：偷\n>\n> \n>\n> `a[i][0] = max(a[i-1][0], a[i-1][1]) `\n>\n> `a[i][1] = a[i-1][0] + nums[i]`\n\n```java\nclass Solution {\n    public int rob(int[] nums) {\n        if (nums == null || nums.length == 0) {\n            return 0;\n        }\n\n        int n = nums.length;\n        int[][] dp = new int[n][2];\n        dp[0][0] = 0;\n        dp[0][1] = nums[0];\n\n        for(int i = 1; i < n; i++) {\n            dp[i][0] = Math.max(dp[i-1][0], dp[i-1][1]);\n            dp[i][1] = dp[i-1][0] + nums[i];\n        }\n\n        return Math.max(dp[n-1][0], dp[n-1][1]);\n    }\n}\n```\n\n> `a[i] `: 0...i ，且包含了 `nums[i]` 必偷的情形，max value: max(a)\n>\n> `a[i] = max(a[i-1], a[i-2] + nums[i])`\n\n```java\nclass Solution {\n    public int rob(int[] nums) {\n        if (nums == null || nums.length == 0) {\n            return 0;\n        }\n        if (nums.length == 1) return nums[0];\n\n        int n = nums.length;\n        int[] dp = new int[n];\n        dp[0] = nums[0];\n        dp[1] = Math.max(nums[0], nums[1]);\n        int res = Math.max(dp[0], dp[1]);\n\n        for(int i = 2; i < n; i++) {\n            dp[i] = Math.max(dp[i-1], dp[i-2] + nums[i]);\n            res = Math.max(res, dp[i]);\n        }\n\n        return res;\n    }\n}\n```\n\n#### 股票问题 [分析](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/solution/yi-ge-fang-fa-tuan-mie-6-dao-gu-piao-wen-ti-by-l-3/)\n\n\n\n### Trie\n\n#### [208. implement trie prefix tree](https://leetcode-cn.com/problems/implement-trie-prefix-tree/)\n\n```java\nclass Trie {\n\n    private TrieNode root;\n\n    /** Initialize your data structure here. */\n    public Trie() {\n        this.root = new TrieNode('/');\n    }\n    \n    /** Inserts a word into the trie. */\n    public void insert(String word) {\n        TrieNode p = root;\n        for (int i = 0; i < word.length(); i++) {\n            int index = word.charAt(i) - 'a';\n            if (p.children[index] == null) {\n                TrieNode newNode = new TrieNode(word.charAt(i));\n                p.children[index] = newNode;\n            }\n            p = p.children[index];\n        }\n        p.isEndingChar = true;\n    }\n    \n    /** Returns if the word is in the trie. */\n    public boolean search(String word) {\n        TrieNode p = root;\n        for (int i = 0; i < word.length(); i++) {\n            int index = word.charAt(i) - 'a';\n            if (p.children[index] == null) {\n                return false;\n            }\n            p = p.children[index];\n        }\n        if (p.isEndingChar) return true;\n        else return false;\n    }\n    \n    /** Returns if there is any word in the trie that starts with the given prefix. */\n    public boolean startsWith(String prefix) {\n        TrieNode p = root;\n        for (int i = 0; i < prefix.length(); i++) {\n            int index = prefix.charAt(i) - 'a';\n            if (p.children[index] == null) {\n                return false;\n            }\n            p = p.children[index];\n        }\n        return true;\n    }\n\n    class TrieNode {\n        public char data;\n        public TrieNode[] children = new TrieNode[26];\n\t    public boolean isEndingChar = false;\n    \n        public TrieNode(char data) {\n            this.data = data;\n        }\n    }\n}\n\n/**\n * Your Trie object will be instantiated and called as such:\n * Trie obj = new Trie();\n * obj.insert(word);\n * boolean param_2 = obj.search(word);\n * boolean param_3 = obj.startsWith(prefix);\n */\n```\n\n#### [212. word search ii](https://leetcode-cn.com/problems/word-search-ii/)\n\n> 1、words 遍历 --> board 中 search    \n>\n> 2、Trie\n>\n> a. all words --> Trie \n>\n> b. board --> DFS\n\n```python\ndx = [-1, 1, 0, 0]\ndy = [0, 0, -1, 1]\nEND_OF_WORD = \"#\"\n\nclass Solution(object):\n    def findWords(self, board, words):\n        \"\"\"\n        :type board: List[List[str]]\n        :type words: List[str]\n        :rtype: List[str]\n        \"\"\"\n        if not board or not board[0]: return []\n        if not words: return []\n        \n        self.result = set()\n        \n        # 根据words构建Trie\n        root = {}\n        for word in words:\n            node = root\n            for char in word:\n                node = node.setdefault(char, {})\n            node[END_OF_WORD] = END_OF_WORD\n        \n        self.m, self.n = len(board), len(board[0])\n        for i in range(self.m):\n            for j in range(self.n):\n                if board[i][j] in root: # 剪枝\n                    self._dfs(board, i, j, \"\", root)\n        \n        return list(self.result)\n    \n    def _dfs(self, board, i, j, cur_word, cur_dict):\n        # terminator\n        cur_word += board[i][j]\n        cur_dict = cur_dict[board[i][j]]\n        if END_OF_WORD in cur_dict:\n            self.result.add(cur_word)\n        \n        # process current logic\n        tmp, board[i][j] = board[i][j], '@'  # @表示 board[i][j]用过了，就不再用了\n       \n    \t# drill down\n    \tfor k in range(4):\n            x, y = i + dx[k], j + dy[k]\n            if 0 <= x < self.m and 0 <= y < self.n and board[x][y] != '@' and board[x][y] in cur_dict:\n                self._dfs(board, x, y, cur_word, cur_dict)\n        \n        # 恢复 board\n        board[i][j] = tmp  \n```\n\n\n\n### Sort\n\n#### [242. valid anagram](https://leetcode-cn.com/problems/valid-anagram/)\n\n```java\nclass Solution {\n    public boolean isAnagram(String s, String t) {\n        if (s.length() != t.length()) return false;\n        char[] sArray = s.toCharArray();\n        char[] tArray = t.toCharArray();\n        Arrays.sort(sArray);\n        Arrays.sort(tArray);\n        return Arrays.equals(sArray, tArray);\n    }\n}\n```\n\n### 位运算\n\n#### [231. power of two](https://leetcode-cn.com/problems/power-of-two/)\n\n\n\n\n"
  },
  {
    "path": "leetcode/src/linkedlistcycle_141/LinkedListCycle.java",
    "content": "package linkedlistcycle_141;\n\n/**\n * 141. Linked List Cycle\n * https://leetcode.com/problems/linked-list-cycle/\n */\npublic class LinkedListCycle {\n    public boolean hasCycle(ListNode head) {\n        if (head == null || head.next == null) {\n            return false;\n        }\n\n        ListNode fast = head;\n        ListNode slow = head;\n\n        while (fast != null && fast.next != null) {\n            fast = fast.next.next;\n            slow = slow.next;\n            if (fast == slow) return true;\n        }\n\n        return false;\n    }\n\n    public static class ListNode {\n        int val;\n        ListNode next;\n        ListNode(int x) { val = x;}\n    }\n}\n"
  },
  {
    "path": "leetcode/src/lrucache_146/LRUCache.java",
    "content": "package lrucache_146;\n\n\nimport java.util.HashMap;\n\n/**\n * 146. LRU Cache\n * https://leetcode.com/problems/lru-cache/description/\n */\npublic class LRUCache {\n    private Node head;\n    private Node tail;\n    private HashMap<Integer, Node> map;\n    private int capacity;\n\n    public LRUCache(int capacity) {\n        this.capacity = capacity;\n        this.map = new HashMap<>(capacity * 4 / 3);\n\n        head = new Node(-1,-1);\n        tail = new Node(-1,-1);\n\n        head.next = tail;\n        tail.pre = head;\n    }\n\n    public int get(int key) {\n        // key 不存在\n        if (!map.containsKey(key)) {\n            return -1;\n        }\n\n        // key 存在\n        Node node = map.get(key);\n        delete(node);\n        insertToHead(node);\n\n        return node.value;\n    }\n\n    public void put(int key, int value) {\n        // key 存在\n        if (map.containsKey(key)) {\n            Node node = map.get(key);\n            delete(node);\n        }\n        // key 不存在\n        Node node = new Node(key, value);\n        insertToHead(node);\n        map.put(key, node);\n\n        if (map.size() > capacity) {\n            Node remove = deleteTail();\n            map.remove(remove.key);\n        }\n    }\n\n    private void delete(Node node) {\n        Node next = node.next;\n        Node pre = node.pre;\n\n        pre.next = next;\n        next.pre = pre;\n\n        node.next = null;\n        node.pre = null;\n    }\n\n    private void insertToHead(Node node) {\n        Node next = head.next;\n        node.next = next;\n        node.pre = head;\n\n        next.pre = node;\n        head.next = node;\n    }\n\n    private Node deleteTail() {\n        Node node = tail.pre;\n\n        Node pre = node.pre;\n        tail.pre = pre;\n        pre.next = tail;\n\n        node.next = null;\n        node.pre = null;\n\n        return node;\n    }\n\n    private class Node {\n        int key;\n        int value;\n        Node pre;\n        Node next;\n\n        public Node (int key, int value) {\n            this.key = key;\n            this.value = value;\n        }\n    }\n}\n"
  },
  {
    "path": "leetcode/src/mergetwosortedlist_21/Merge2SortedLists.java",
    "content": "package mergetwosortedlist_21;\n\n/**\n * 21. Merge Two Sorted Lists\n * https://leetcode.com/problems/merge-two-sorted-lists/\n */\npublic class Merge2SortedLists {\n    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {\n        if (l1 == null) return l2;\n        if (l2 == null) return l1;\n\t\n\t// 利用哨兵（前哨节点）简化实现难度\n        ListNode outpost = new ListNode(-1);\n        ListNode temp = outpost;\n\n        while (l1 != null && l2 != null) {\n            if (l1.val <= l2.val) {\n                temp.next = l1;\n                l1 = l1.next;\n            } else {\n                temp.next = l2;\n                l2 = l2.next;\n            }\n\n            temp = temp.next;\n        }\n\n        if (l1 == null) {\n            temp.next = l2;\n        }\n\n        if (l2 == null) {\n            temp.next = l1;\n        }\n\n        return outpost.next;\n    }\n\t\n\tpublic ListNode mergeTwoListsRecur(ListNode l1, ListNode l2) {\n        if (l1 == null) return l2;\n        if (l2 == null) return l1;\n\t\tif (l1.val < l2.val) {\n\t\t\tl1.next = mergeTwoListsRecur(l1.next, l2);\n\t\t\treturn l1;\n\t\t} else {\n\t\t\tl2.next = mergeTwoListsRecur(l1, l2.next);\n\t\t\treturn l2;\n\t\t}\n\t}\n\n    public static class ListNode {\n        int val;\n        ListNode next;\n        ListNode(int x) { val = x;}\n    }\n}\n"
  },
  {
    "path": "leetcode/src/middleofthelinkedlist_876/MiddleNode.java",
    "content": "package middleofthelinkedlist_876;\n\n/**\n * 876. Middle of the Linked List\n * https://leetcode.com/problems/middle-of-the-linked-list/\n */\npublic class MiddleNode {\n    public ListNode middleNode(ListNode head) {\n        ListNode fast = head;\n        ListNode slow = head;\n\n        while (fast != null && fast.next != null) {\n            fast = fast.next.next;\n            slow = slow.next;\n        }\n\n        return slow;\n    }\n\n\n    public static class ListNode {\n        int val;\n        ListNode next;\n        ListNode(int x) { val = x;}\n    }\n}\n\n\n"
  },
  {
    "path": "leetcode/src/palindromelinkedlist_234/PalindromeLinkedList.java",
    "content": "package palindromelinkedlist_234;\n\n/**\n * 234. Palindrome Linked List\n * https://leetcode.com/problems/palindrome-linked-list/\n * Solution:\n * 1. 找到中间节点，将单链表后半段逆置\n * 2. 左半段从左到右，右半段从右到左，比较2段链表是否对应相等\n * 3. 对比完之后，最好能将右半段逆置，还原链表\n * 示例：\n * 1->2->2->1\n * 1->2->2<-1  (第2个2指向null)\n */\npublic class PalindromeLinkedList {\n    public boolean isPalindrome(ListNode head) {\n        // 1. 找到单链表的中间节点\n        ListNode fast = head;\n        ListNode slow = head;\n\n        while (fast != null && fast.next != null) {\n            fast = fast.next.next;\n            slow = slow.next;   // 此时slow就是中间节点\n        }\n\n        // 2. 从中间节点开始，将右半段链表逆置\n        ListNode pre = null;\n        ListNode next = null;\n\n        while (slow != null) {\n            next = slow.next;\n            slow.next = pre;\n            pre = slow;\n            slow = next;\n        }\n\n        // 3. 左半段从左到右，右半段从右到左，比较2段链表是否对应相等\n        fast = head;\n        slow = pre;\n\n        while (slow != null) {\n            if (fast.val != slow.val) {\n                return false;\n            }\n            fast = fast.next;\n            slow = slow.next;\n        }\n\n        // 4. 对比完之后，最好能将右半段逆置，还原链表\n\n        return true;\n\n    }\n\n\n    public static class ListNode {\n        int val;\n        ListNode next;\n        ListNode(int x) {\n            this.val = val;\n        }\n    }\n}\n"
  },
  {
    "path": "leetcode/src/removenthnodefromendoflist_19/RemoveNthNodeFromEndOfList.java",
    "content": "package removenthnodefromendoflist_19;\n\n/**\n* 19. Remove Nth Node From End of List\n* https://leetcode.com/problems/remove-nth-node-from-end-of-list/\n*/\npublic class RemoveNthNodeFromEndOfList {\n    public ListNode removeNthFromEnd(ListNode head, int n) {\n        ListNode p1 = head;\n\n        for (int i = 0; i < n; i++) {\n            p1 = p1.next;\n        }\n\n        ListNode p2 = head; // 要删除的节点\n        ListNode pre = null;\n\n        while (p1 != null) {\n            p1 = p1.next;\n            pre = p2;\n            p2 = p2.next;\n        }\n\n        if (p2 == head) {  // 要删除的节点为head,特殊处理\n            head = head.next;\n        } else {\n            pre.next = p2.next;\n            p2.next = null;\n        }\n\n        return head;\n    }\n\n    public static class ListNode {\n        int val;\n        ListNode next;\n        ListNode(int x) {\n            this.val = val;\n        }\n    }\n}\n"
  },
  {
    "path": "leetcode/src/reverselinkedlist_206/ReverseList.java",
    "content": "package reverselinkedlist_206;\n\n/**\n * 206. Reverse Linked List\n * https://leetcode.com/problems/reverse-linked-list/\n */\npublic class ReverseList {\n    public ListNode reverseList(ListNode head) {\n        if (head == null || head.next == null) return head;\n\n        ListNode pre = null;\n        ListNode next = null;\n\n        while (head != null) {\n            next = head.next;\n            head.next = pre;\n            pre = head;\n            head = next;\n        }\n\n        return pre;\n    }\n\n    public static class ListNode {\n        int val;\n        ListNode next;\n        ListNode(int x) {\n            this.val = val;\n        }\n    }\n}\n\n\n\n\n\n"
  },
  {
    "path": "leetcode/src/threesum_015/ThreeSum.java",
    "content": "package threesum_015;\n\npublic class ThreeSum {\n}\n"
  },
  {
    "path": "leetcode/src/twosum_001/TwoSum.java",
    "content": "package twosum_001;\n\npublic class TwoSum {\n    public static void main(String[] args) {\n\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Attention.txt",
    "content": "- 面试沟通\n    (1)面试时，要经常和面试官沟通。沟通好题目条件、问题的意图之后再动手coding或者回答问题。\n    (2)面试中，若面试官提出新的概念，面试者需要和面试官积极沟通，多问几个问题，把概念搞清楚。\n    (3)面试中，若有多种解法，且多种解法各有优缺点，则需要和面试官沟通，确定问题需要的最合适的解法。\n    (4)考虑性能的时候，是关注时间还是空间？其复杂度要求是多少？\n        考虑实现的时候，是否可以修改原来的结构？是否可以在新的结构中操作?\n\n- 排序和查找\n    --查找：顺序查找 二分查找 哈希表查找 二叉排序树（其实就是二叉搜索树）查找\n    (1) 二分查找：要求在排序或者是部分排序的数组中查找一个数字或者统计某个数字出现的次数，可以尝试二分查找。\n    (2) 哈希表&二叉排序树：重点在于考察数据结构本身，不在于算法\n    (3) 哈希表：优点是能够在O(1)内找到某一个元素，是效率最高的查找方式。缺点是需要额外空间实现哈希表。\n\n    -- 排序：插入排序 冒泡排序 归并排序 快速排序\n    关注其实现，性能，场景等\n\n- 回溯法：\n    （1）类似于暴力解答\n    （2）常常使用递归，回溯法很适合递归实现。递归可以用栈来模拟。\n    注：二维数组或者迷宫问题，可以尝试回溯法。\n\n- 递归与循环：\n    (1)递归：由于递归实现更加简洁，若没有特殊要求，可以优先选用递归实现。\n    效率问题：递归可能存在大量的重复运算，因此性能可能弱于循环。如：Ex_10_Fibonacci\n    栈溢出问题：递归还可能引起调用栈溢出的问题。\n\n    (2)思考：一般用递归的方式思考答案，用循环的方式实现代码。\n\n- 动态规划\n    （1）动态规划多可以用递归解决；\n    （2）但是递归中有很多需要重复计算的项，如Ex_10_Fibonacci\n    （3）动态规划从下到上，将重复的子问题的答案存储起来，减少了重复计算的时间浪费，但是增加了空间的消耗。\n\n- 贪心算法\n\n- 说明\n    (1) 若求某个问题的最优解，且该问题可以分解为多个子问题，则可以尝试动态规划。\n    递归操作是自上而下，动态规划则是自下而上，避免不必要的重复计算。\n    若是某个问题有特殊的选择，那么这个问题的最优解可能就是贪婪算法得出的。\n    (2) 思考路线：递归->动态规划->贪婪算法\n\n- 位运算\n    (1) 基本运算：与、或、异或、左移、右移\n    (2) 把一个整数减1之后再和原来的整数做位与运算，相当于将整数的二进制表示中的最右边的1变成0：\n    x = (x - 1) & x : 将x的二进制最右边的1变成了0\n\n- 高质量的代码\n    -- 代码的规范性\n    （1）书写清晰\n    （2）布局清晰\n    （3）命名合理\n    -- 代码的完整性\n    （1）功能测试：基本功能\n    （2）边界测试：边界值\n    （3）负面测试：非法值\n\n    -- 代码的鲁棒性：程序对输入的合法性判断以及对非法输入的处理\n        --- 容错性\n        --- 防御性编程\n\n    --注：在处理链表问题时，当我们用一个指针遍历链表无法解决问题时，可以尝试用2个指针解决问题。\n    可以让一个指针遍历的速度快一点（一次走2步，或者先走若干步），让另外一个指针遍历的速度慢一点\n\n     --注：\n        （1）若面试题是关于n位的整数且没有限定n的取值范围，或者输入任意大小的整数，则此题目可能需要考虑大数问题。\n        （2）大数问题如何处理？字符串是一种有效的地表示大数地方法。\n        （3）例：Ex_17_AddTwoBigNumber\n\n- 解决面试题的思路\n    -- 在解决笔试或者面试题目之前，应该思考清楚题目的解决思路，然后再进行编码。\n\n    -- 画图\n    -- 举例\n    -- 分解\n\n    -- 注：\n    1. 二叉树遍历\n        -- 先序             Stack T26:树的子结构; T7:重建二叉树 T37：树的序列化和反序列化\n        -- 中序             Stack T7:重建二叉树\n        -- 后序             Stack T33:判断一个序列是否是BST的后序（先序）遍历序列；\n        -- Morris遍历       Stack\n        -- 宽度优先遍历：层遍历（也叫广度优先遍历）T32：从上到下打印二叉树\n            -- 不分行       Queue\n            -- 分行         Queue + 记录节点\n            -- 之字形       Stack * 2\n        -- 深度优先遍历：先序遍历   T34：二叉树中和为某一个值的路径\n\n    2. 二叉树分类\n        -- 二叉搜索树\n        -- 红黑树\n        -- 二叉堆\n    3. 技巧：\n        -- 若要求处理二叉树的遍历序列，则可以先找到二叉树的根节点，\n        然后基于根节点将二叉树的遍历序列分成左子树和右子树对应的子序列 分界：i\n        然后递归处理这2个子序列.模式如下\n        process(sequence, start, end)\n        -> process(sequence, start, i-1)\n        -> process(sequence, i, end)\n            --- 例如：面试题33：判断一个序列是否是BST的后序（先序）遍历序列；\n                      面试题7：重建二叉树\n\n- 优化时间和空间效率\n\n-- 注：若需要判断多个字符是否在某个字符串中出现过或者统计其出现的次数，考虑哈希表，或者考虑基于数组创建一个简单的哈希表，\n这样可以用很小得空间消耗换来时间效率的提升。\n\n-- 如何降低时间复杂度？\n1. 改用更高效的算法\n2. 空间换时间\n\n\n-- 递归与动态规划\n\n- 面试考察能力\n\n--编程能力\n--学习能力\n--抽象建模能力\n--发散思维能力\n--知识迁移能力\n--沟通能力\n\n*******************************************************\n- 编写程序时需要考虑的一些问题：\n-- 关注鲁棒性：边界条件 特殊输入 错误处理等\n-- 编写过程：\n   测试用例\n   -> 找出规律\n   -> 编程\n   -> 检验 （基本功能、边界条件、错误处理）\n   -> 优化"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_03_FindDuplicatedNumInArray.java",
    "content": "package com.ex.offer;\n\nimport java.util.HashMap;\n\n/**\n * problem 3: 数组中重复的数字\n * 在一个长度为n的数组里的所有数字都在0到n-1的范围内。\n * 数组中某些数字是重复的，但不知道有几个数字是重复的。\n * 也不知道每个数字重复几次。请找出数组中任意一个重复的数字。\n * 例如，如果输入长度为7的数组{2,3,1,0,2,5,3}，那么对应的输出是第一个重复的数字2。\n */\npublic class Ex_03_FindDuplicatedNumInArray {\n\n    public boolean duplicate(int numbers[], int [] duplication) {\n        if (numbers == null || numbers.length < 2) {\n            return false;\n        }\n\n        HashMap<Integer, Integer> map = new HashMap<>();\n        for (int i = 0; i < numbers.length; i++) {\n            if (!map.containsKey(numbers[i])) {\n                map.put(numbers[i], 1);\n            } else {\n                duplication[0] = numbers[i];\n                return true;\n            }\n        }\n        return false;\n    }\n\n    /**\n     * 由于numbers数组中的元素[0,n-1]\n     * 若没有重复元素，排序之后i位置为i\n     * 若有重复元素，则i位置为i，但是其他位置也可能有i\n     * 思路：\n     * 遍历数组\n     * 若i位置为i,i++\n     * 若i位置不是i\n     * （1）m = numbers[i], 则m的正确位置为numbers[m], 若numbers[m] = m,则重复元素就是m,否则\n     *  (2) 交换m到正确的位置上。\n     * @param numbers\n     * @param duplication\n     * @return\n     */\n    public boolean duplicateImprove(int numbers[], int [] duplication) {\n        if (numbers == null || numbers.length < 2) {\n            return false;\n        }\n\n        for (int i = 0; i < numbers.length; i++) {\n            if (numbers[i] == i) {\n                i++;\n            } else {\n                int m = numbers[i];\n                if (numbers[m] == m) {\n                    duplication[0] = m;\n                    return true;\n                } else {\n                    swap(numbers, i, m);\n                }\n            }\n        }\n        return false;\n    }\n\n    private static void swap(int[] arr, int i, int j) {\n        int tmp = arr[i];\n        arr[i] = arr[j];\n        arr[j] = tmp;\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_03_FindDuplicatedNumInWithoutChangeArray.java",
    "content": "package com.ex.offer;\n\n/**\n * problem 3: 不修改数组找出重复的数字。 [binary search]\n *\n * 特性：若数组中没有重复元素，则[x,y]范围内的数字个数为y-x+1,若超出这个个数,则说明有重复的数字。\n */\npublic class Ex_03_FindDuplicatedNumInWithoutChangeArray {\n\n    public static int duplicate(int numbers[]) {\n        if (numbers == null || numbers.length < 2) {\n            return -1;\n        }\n\n        int start = 1;\n        int end = numbers.length - 1;\n\n        while(start <= end) {\n            int mid = start + ((end - start) >> 1);  // 这里 >> 一定要放在括号内\n            int count = countRange(numbers, start, mid);\n\n            if (start == end) {\n                if (count > 1) {\n                    return start;\n                } else {\n                    break;\n                }\n            }\n\n            if (count > (mid - start + 1)) {\n                end = mid;\n            } else {\n                start = mid + 1;\n            }\n        }\n\n        return -1;\n    }\n\n    private static int countRange(int[] numbers, int start, int end) {\n        if (numbers == null) {\n            return 0;\n        }\n\n        int count = 0;\n        for (int i = 0; i < numbers.length; i++) {\n            if (numbers[i] <= end && numbers[i] >= start) {\n                count++;\n            }\n        }\n\n        return count;\n    }\n\n    public static void main(String[] args) {\n        int[] numbers = new int[]{2, 3, 5, 4, 3, 2, 6, 7};\n        int duplicate = duplicate(numbers);\n        System.out.println(duplicate);\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_04_FindNumIn2VArray.java",
    "content": "package com.ex.offer;\n\n/**\n * 1.在一个二维数组中，每一行都按照从左到右递增的顺序排序，\n * 每一列都按照从上到下递增的顺序排序。请完成一个函数，\n * 输入这样的一个二维数组和一个整数，判断数组中是否含有该整数。\n */\npublic class Ex_04_FindNumIn2VArray {\n\n    public static boolean Find(int target, int[][] array) {\n        if (array == null || array.length == 0) {\n            return false;\n        }\n\n        //从右上角向左下遍历\n        int row = 0;\n        int col = array[0].length - 1;\n\n        while (row < array.length && col > -1) {\n            if (array[row][col] == target) {\n                return true;\n            } else if (array[row][col] < target) {\n                row++;\n            } else {\n                col--;\n            }\n        }\n        return false;\n    }\n\n    public static void main(String[] args) {\n        int[][] array = new int[][] { { 0, 1, 2, 3, 4, 5, 6 },// 0\n                { 10, 12, 13, 15, 16, 17, 18 },// 1\n                { 23, 24, 25, 26, 27, 28, 29 },// 2\n                { 44, 45, 46, 47, 48, 49, 50 },// 3\n                { 65, 66, 67, 68, 69, 70, 71 },// 4\n                { 96, 97, 98, 99, 100, 111, 122 },// 5\n                { 166, 176, 186, 187, 190, 195, 200 },// 6\n                { 233, 243, 321, 341, 356, 370, 380 } // 7\n        };\n        int target = 233;\n        System.out.println(Find(target, array));\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_05_ReplaceSpace.java",
    "content": "package com.ex.offer;\n\n/**\n * 2.请实现一个函数，将一个字符串中的空格替换成“%20”。\n * 例如，当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。\n */\npublic class Ex_05_ReplaceSpace {\n    public static String replaceSpace(StringBuffer str) {\n        String s = str.toString();\n        String res = s.replaceAll(\" \", \"%20\");\n        return res;\n    }\n\n    /**\n     * 问题1：替换字符串，是在原来的字符串上做替换，还是新开辟一个字符串做替换！\n     * 问题2：在当前字符串替换，怎么替换才更有效率（不考虑java里现有的replace方法）。\n     * 从前往后替换，后面的字符要不断往后移动，要多次移动，所以效率低下\n     * 从后往前，先计算需要多少空间，然后从后往前移动，则每个字符只移动一次，这样效率更高。\n     *\n     * @param str\n     * @return\n     */\n    public static String replaceBlank(StringBuffer str) {\n        if (str == null) {\n            return null;\n        }\n\n        int spaceNum = 0;\n        for (int i = 0; i < str.length(); i++) {\n            if (str.charAt(i) == ' ') {\n                spaceNum++;\n            }\n        }\n\n        int len = str.length() + 2 * spaceNum;\n        int indexOld = str.length() - 1;\n        int indexNew = len - 1;\n        str.setLength(len);\n\n        while (indexOld >= 0) {\n            if (str.charAt(indexOld) == ' ') {\n                str.setCharAt(indexNew--, '0');\n                str.setCharAt(indexNew--, '2');\n                str.setCharAt(indexNew--, '%');\n\n            } else {\n                str.setCharAt(indexNew--, str.charAt(indexOld));\n            }\n\n            indexOld--;\n        }\n\n        return str.toString();\n    }\n\n    public static void main(String[] args) {\n        StringBuffer str = new StringBuffer();\n        str.append(\"We Are Happy\");\n        String s = replaceBlank(str);\n        System.out.print(s);\n\n        System.out.println();\n\n        StringBuffer str1 = new StringBuffer();\n        str1.append(\"\");\n        String s1 = replaceBlank(str1);\n        System.out.print(s1);\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_06_PrintListFromTailToHead.java",
    "content": "package com.ex.offer;\n\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.Stack;\n\npublic class Ex_06_PrintListFromTailToHead {\n\n    public static ArrayList<Integer> printListFromTailToHead(ListNode listNode) {\n        if (listNode == null) {\n            return new ArrayList<>();\n        }\n\n        Stack<Integer> stack = new Stack<>();\n        ArrayList<Integer> list = new ArrayList<>();\n        for (ListNode node = listNode; node != null; node = node.next) {\n            stack.push(node.val);\n        }\n\n        while(!stack.isEmpty()) {\n            list.add(stack.pop());\n        }\n\n        return list;\n    }\n\n    public static ArrayList<Integer> printListFromTailToHeadRecur(ListNode listNode) {\n        ArrayList<Integer> list = new ArrayList<>();\n\n        if (listNode != null) {\n\n            if (listNode.next != null) {\n                ArrayList<Integer> temp = new ArrayList<>();\n                temp = printListFromTailToHeadRecur(listNode.next);\n                for (Integer i : temp) {\n                    list.add(i);\n                }\n            }\n\n            list.add(listNode.val);\n        }\n\n        return list;\n    }\n\n    public static ArrayList<Integer> printListFromTailToHeadWithCollections(ListNode listNode) {\n        ArrayList<Integer> list = new ArrayList<>();\n\n        for (ListNode p = listNode; p != null; p = p.next) {\n            list.add(p.val);\n        }\n\n        Collections.reverse(list);\n        return list;\n    }\n\n    public static void main(String[] args) {\n        ListNode head = new ListNode(1);\n        head.next = new ListNode(2);\n        head.next.next = new ListNode(3);\n        head.next.next.next = new ListNode(4);\n\n        ArrayList<Integer> list = new ArrayList<>();\n        list = printListFromTailToHeadRecur(head);\n\n    }\n}\n\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_07_ReConstructBT.java",
    "content": "package com.ex.offer;\n\n/**\n * 4.输入某二叉树的前序遍历和中序遍历的结果，请重建出该二叉树。\n * 假设输入的前序遍历和中序遍历的结果中都不含重复的数字。\n * 例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6}，\n * 则重建二叉树并返回。\n *\n * 思路：\n * 1.pre负责确定树的root;\n * 2.in负责确定树的root.left,root.right,即左右子树;\n * 3.递归1,2\n */\npublic class Ex_07_ReConstructBT {\n\n    public static TreeNode reConstructBinaryTree(int[] pre, int[] in) {\n        if (pre == null || in == null || pre.length == 0 || in.length == 0) {\n            return null;\n        }\n        TreeNode root = reConstructBinaryTree(pre, 0, pre.length-1, in, 0, in.length-1);\n        return root;\n    }\n\n    private static TreeNode reConstructBinaryTree(int[] pre, int preStart, int preEnd, int[] in, int inStart, int inEnd) {\n        if (preStart > preEnd || inStart > inEnd) {\n            return null;\n        }\n\n        TreeNode root = new TreeNode(pre[preStart]);\n        for (int i = inStart; i <= inEnd; i++) {\n            if (in[i] == pre[preStart]) {\n                root.left = reConstructBinaryTree(pre, preStart+1, preStart+(i-inStart), in, inStart, i-1);\n                root.right = reConstructBinaryTree(pre, preStart + 1 + (i-inStart), preEnd, in, i+1, inEnd);\n                break;\n            }\n        }\n        return root;\n    }\n\n}\n\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_08_DescendantNode.java",
    "content": "package com.ex.offer;\n\npublic class Ex_08_DescendantNode {\n\n\tpublic static class Node {\n\t\tpublic int value;\n\t\tpublic Node left;\n\t\tpublic Node right;\n\t\tpublic Node parent;\n\n\t\tpublic Node(int data) {\n\t\t\tthis.value = data;\n\t\t}\n\t}\n\n\tpublic static Node getNextNode(Node node) {\n\t\tif (node == null) {\n\t\t\treturn node;\n\t\t}\n\t\tif (node.right != null) {\n\t\t\treturn getLeftMost(node.right);\n\t\t} else {\n\t\t\tNode parent = node.parent;\n\t\t\twhile (parent != null && parent.left != node) {\n\t\t\t\tnode = parent;\n\t\t\t\tparent = node.parent;\n\t\t\t}\n\t\t\treturn parent;\n\t\t}\n\t}\n\n\tpublic static Node getLeftMost(Node node) {\n\t\tif (node == null) {\n\t\t\treturn node;\n\t\t}\n\t\twhile (node.left != null) {\n\t\t\tnode = node.left;\n\t\t}\n\t\treturn node;\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tNode head = new Node(6);\n\t\thead.parent = null;\n\t\thead.left = new Node(3);\n\t\thead.left.parent = head;\n\t\thead.left.left = new Node(1);\n\t\thead.left.left.parent = head.left;\n\t\thead.left.left.right = new Node(2);\n\t\thead.left.left.right.parent = head.left.left;\n\t\thead.left.right = new Node(4);\n\t\thead.left.right.parent = head.left;\n\t\thead.left.right.right = new Node(5);\n\t\thead.left.right.right.parent = head.left.right;\n\t\thead.right = new Node(9);\n\t\thead.right.parent = head;\n\t\thead.right.left = new Node(8);\n\t\thead.right.left.parent = head.right;\n\t\thead.right.left.left = new Node(7);\n\t\thead.right.left.left.parent = head.right.left;\n\t\thead.right.right = new Node(10);\n\t\thead.right.right.parent = head.right;\n\n\t\tNode test = head.left.left;\n\t\tSystem.out.println(test.value + \" next: \" + getNextNode(test).value);\n\t\ttest = head.left.left.right;\n\t\tSystem.out.println(test.value + \" next: \" + getNextNode(test).value);\n\t\ttest = head.left;\n\t\tSystem.out.println(test.value + \" next: \" + getNextNode(test).value);\n\t\ttest = head.left.right;\n\t\tSystem.out.println(test.value + \" next: \" + getNextNode(test).value);\n\t\ttest = head.left.right.right;\n\t\tSystem.out.println(test.value + \" next: \" + getNextNode(test).value);\n\t\ttest = head;\n\t\tSystem.out.println(test.value + \" next: \" + getNextNode(test).value);\n\t\ttest = head.right.left.left;\n\t\tSystem.out.println(test.value + \" next: \" + getNextNode(test).value);\n\t\ttest = head.right.left;\n\t\tSystem.out.println(test.value + \" next: \" + getNextNode(test).value);\n\t\ttest = head.right;\n\t\tSystem.out.println(test.value + \" next: \" + getNextNode(test).value);\n\t\ttest = head.right.right; // 10's next is null\n\t\tSystem.out.println(test.value + \" next: \" + getNextNode(test));\n\t}\n\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_08_GetNextNodeInBT.java",
    "content": "package com.ex.offer;\n\n\n/**\n * 后继节点\n */\npublic class Ex_08_GetNextNodeInBT {\n    public TreeLinkNode GetNext(TreeLinkNode pNode) {\n        if (pNode == null) {\n            return null;\n        }\n\n        if (pNode.right != null) {\n            return getMostLeft(pNode.right);\n        } else {\n            TreeLinkNode parent = pNode.parent;\n            while (parent != null && parent.left != pNode) {\n                pNode = parent;\n                parent = parent.parent;\n            }\n            return parent;\n        }\n    }\n\n    private TreeLinkNode getMostLeft(TreeLinkNode node) {\n        while (node.left != null) {\n            node = node.left;\n        }\n        return node;\n    }\n}\n\n\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_09_QueueWithTwoStack.java",
    "content": "package com.ex.offer;\n\nimport java.util.Stack;\n\n/**\n * problem 9: 用两个栈来实现一个队列，完成队列的Push和Pop操作。 队列中的元素为int类型。\n */\n\npublic class Ex_09_QueueWithTwoStack {\n    Stack<Integer> stack1 = new Stack<Integer>();\n    Stack<Integer> stack2 = new Stack<Integer>();\n\n    public void push(int node) {\n        stack1.push(node);\n    }\n\n    public int pop() {\n        int res = 0;\n        while (!stack1.isEmpty()) {\n            res = stack1.pop();\n            if (!stack1.isEmpty()) {\n                stack2.push(res);\n            }\n        }\n\n        while (!stack2.isEmpty()) {\n            stack1.push(stack2.pop());\n        }\n        return res;\n    }\n\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_09_StackWithTwoQueue.java",
    "content": "package com.ex.offer;\n\nimport java.util.LinkedList;\nimport java.util.Queue;\n\npublic class Ex_09_StackWithTwoQueue {\n\n    Queue<Integer> queue1 = new LinkedList<>();\n    Queue<Integer> queue2 = new LinkedList<>();\n\n    public void push(int node) {\n        queue1.add(node);\n    }\n\n    public int pop() {\n        int res = 0;\n\n        while (!queue1.isEmpty()) {\n            res = queue1.poll();\n\n            if (!queue1.isEmpty()) {\n                queue2.add(res);\n            }\n        }\n\n        while (!queue2.isEmpty()) {\n            queue1.add(queue2.poll());\n        }\n\n        return res;\n    }\n\n    public static void main(String[] args) {\n        Ex_09_StackWithTwoQueue stack = new Ex_09_StackWithTwoQueue();\n        stack.push(1);\n        stack.push(2);\n        stack.push(3);\n        stack.push(4);\n\n        System.out.println(stack.pop());\n        System.out.println(stack.pop());\n        System.out.println(stack.pop());\n        System.out.println(stack.pop());\n        System.out.println(stack.pop());\n        System.out.println(stack.pop());\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_10_Fibonacci.java",
    "content": "package com.ex.offer;\n\npublic class Ex_10_Fibonacci {\n\n    public static int fib1(int n) {\n        if (n <= 0) {\n            return 0;\n        }\n        if (n == 1) {\n            return 1;\n        }\n\n        return  fib1(n-1) + fib1(n-2);\n    }\n\n    /**\n     * |Fn+1  Fn   |   |1 1|^n\n     * |Fn    Fn-1 |   |1 0|\n     * @param n\n     * @return\n     */\n    public static int fib2(int n) {\n        return -1;\n    }\n\n    public static int Fibonacci(int n) {\n        if (n <= 0) {\n            return 0;\n        }\n\n        if (n == 1) {\n            return 1;\n        }\n\n        int fib1 = 0;\n        int fib2 = 1;\n\n        int fibN = 0;\n\n        for (int i = 2; i <= n; i++) {\n            fibN = fib1 + fib2;\n\n            fib1 = fib2;\n            fib2 = fibN;\n        }\n        return fibN;\n    }\n\n    public static void main(String[] args) {\n        int n = 5;\n        System.out.println(fib1(n));\n        System.out.println(Fibonacci(n));\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_10_JumpFloor.java",
    "content": "package com.ex.offer;\n\npublic class Ex_10_JumpFloor {\n\n    public int jumpFloor(int target) {\n        if (target == 1 || target == 2) {\n            return target;\n        }\n\n        return jumpFloor(target - 1) + jumpFloor(target - 2);\n    }\n\n    public int JumpFloor(int target) {\n        if (target == 1 || target == 2) {\n            return target;\n        }\n\n        int jump1 = 1;\n        int jump2 = 2;\n        int jumpN = 0;\n\n        for (int i = 3; i <= target; i++) {\n            jumpN = jump1 + jump2;\n\n            jump1 = jump2;\n            jump2 = jumpN;\n        }\n\n        return jumpN;\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_10_JumpFloorII.java",
    "content": "package com.ex.offer;\n\n/**\n * f(n)\n * f(1) = 1;\n * f(2) = f(2-1) + f(2-2) = 1 + 1 = 2;\n * f(3) = f(3-1) + f(3-2) + f(3-2)\n *        = f(0) + f(1) + f(2)\n * f(n-1) = f(0) + f(1) + f(2) + ... + f(n-2)\n * f(n)   = f(0) + f(1) + f(2) + ... + f(n-2) + f(n-1)\n *        = f(n-1) + f(n-1)\n *        = 2 * f(n-1)\n *        = 2 ^ 2 * f(n-2)\n *        = ...\n *        = 2 ^ (n-1) * f(1)\n *        = 2 ^ (n-1)\n *\n * f(n) = 2 ^ (n-1)\n */\npublic class Ex_10_JumpFloorII {\n\n    public static int JumpFloorII(int target) {\n        if (target == 1) {\n            return 1;\n        }\n        int res = 1;\n        for (int i = 1; i < target; i++) {\n            res *= 2;\n        }\n\n        return res;\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_10_RectCover.java",
    "content": "package com.ex.offer;\n\npublic class Ex_10_RectCover {\n    public int RectCover(int target) {\n        if (target == 1 || target == 2) {\n            return target;\n        }\n\n        int rect1 = 1;\n        int rect2 = 2;\n\n        int rectN = 0;\n\n        for (int i = 3; i <= target; i++) {\n            rectN = rect1 + rect2;\n\n            rect1 = rect2;\n            rect2 = rectN;\n        }\n\n        return rectN;\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_11_MinNumOfRotatingArray.java",
    "content": "package com.ex.offer;\n\n/**\n * 把一个数组最开始的若干个元素搬到数组的末尾，我们称之为数组的旋转。\n * 输入一个非递减排序的数组的一个旋转，输出旋转数组的最小元素。\n * 例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转，该数组的最小值为1。\n * NOTE：给出的所有元素都大于0，若数组大小为0，请返回0。\n */\npublic class Ex_11_MinNumOfRotatingArray {\n\n    public static int minNumberInRotateArray(int [] array) {\n        if (array == null || array.length <= 0) {\n            return 0;\n        }\n\n        int low = 0;\n        int high = array.length - 1;\n        int mid = low;  // 若是旋转数组本身，则第一个元素是最小值，直接不进入循环\n\n        // 在这里，假设前面的递增数组第一个元素 > 后面的递增数组最后一个元素\n        while (array[low] >= array[high]) {\n            if (high - low == 1) {\n                mid = high;\n                break;\n            }\n\n            mid = low + (high - low) / 2;\n\n            // 如果arr[low] == array[mid] == array[high],\n            // 则无法用中间和两边比较的方式判断mid属于左边的递增序列还是右边的递增序列\n            if (array[low] == array[high] && array[low] == array[mid]) {\n                return minInOrder(array, low, high);\n            }\n\n            if (array[mid] >= array[low]) {  // 此时，mid位于第一个递增数组中，因此min位于第二个递增数组中\n                low = mid;\n            } else if (array[mid] <= array[high]){\n                high = mid;\n            }\n        }\n\n        return array[mid];\n    }\n\n    private static int minInOrder(int[] array, int low, int high) {\n        int min = array[low];\n        for (int i = low + 1; i <= high; i++) {\n            if (array[i] < min) {\n                min = array[i];\n            }\n        }\n        return min;\n    }\n\n    public static void main(String[] args) {\n        int[] array = new int[]{3,4,5,1,2};\n        int[] array1 = new int[]{1,2,3,4,5};\n        System.out.println(minNumberInRotateArray(array));\n        System.out.println(minNumberInRotateArray(array1));\n\n        int[] array2 = new int[]{1, 0, 1, 1, 1};\n        int[] array3 = new int[]{1, 1, 1, 0, 1};\n        System.out.println(minNumberInRotateArray(array2));\n        System.out.println(minNumberInRotateArray(array3));\n\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_11_SortAges.java",
    "content": "package com.ex.offer;\n\npublic class Ex_11_SortAges {\n\n    // counting sort\n    public static void sortAges(int[] ages) {\n        if (ages == null || ages.length <= 0) {\n            return;\n        }\n\n        int maxAge = 99;\n        int[] countAge = new int[maxAge + 1];  // 0~99\n\n        for (int i = 0; i < ages.length; i++) {\n            countAge[ages[i]]++;\n        }\n\n        int index = 0;\n        for (int i = 0; i <= maxAge; i++) {                  // i:年龄\n            for (int j = 0; j < countAge[i]; j++) {          // j:年龄的个数\n                ages[index++] = i;\n            }\n        }\n\n    }\n\n\n    public static void printArray(int[] arr) {\n        for (int i : arr) {\n            System.out.print(i + \" \");\n        }\n        System.out.println();\n    }\n\n    public static void main(String[] args) {\n        int[] ages = new int[]{2, 8, 99, 6, 20, 99, 88, 77 ,99, 44, 55, 55, 77, 23, 18};\n        printArray(ages);\n        sortAges(ages);\n        printArray(ages);\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_12_HasPathInMatrix.java",
    "content": "package com.ex.offer;\n\npublic class Ex_12_HasPathInMatrix {\n\n    public static boolean hasPath(char[] matrix, int rows, int cols, char[] str) {\n        if (matrix == null || matrix.length <= 0 || str == null || str.length <= 0 ||\n                rows <= 0 || cols <= 0 || matrix.length != rows * cols || matrix.length < str.length) {\n            return false;\n        }\n\n        boolean[] visited = new boolean[rows * cols];\n        int pathLength = 0;\n\n        for (int i = 0; i < rows; i++) {\n            for (int j = 0; j < cols; j++) {\n                if (hasPathCore(matrix, rows, cols,str, i, j, visited, pathLength)) {\n                    return true;\n                }\n            }\n        }\n\n        return false;\n    }\n\n    public static boolean hasPathCore(char[] matrix, int rows, int cols, char[] str, int rowStart, int colStart,\n                               boolean[] visited, int pathLength) {\n        boolean flag = false;\n\n        if (rowStart >= 0 && rowStart < rows && colStart >= 0 && colStart < cols &&\n                !visited[rowStart*cols+colStart] && matrix[rowStart*cols+colStart] == str[pathLength]) {\n            pathLength++;\n            visited[rowStart*cols+colStart] = true;\n\n            if (pathLength == str.length) {\n                return true;\n            }\n\n            flag = hasPathCore(matrix, rows, cols, str, rowStart, colStart+1, visited, pathLength) ||\n                    hasPathCore(matrix, rows, cols, str, rowStart+1, colStart, visited, pathLength) ||\n                    hasPathCore(matrix, rows, cols, str, rowStart, colStart-1, visited, pathLength) ||\n                    hasPathCore(matrix, rows, cols, str, rowStart-1, colStart, visited, pathLength);\n\n            if (!flag) {\n                pathLength--;\n                visited[rowStart*cols+colStart] = false;\n            }\n        }\n\n        return flag;\n    }\n\n    public static void main(String[] args) {\n        String m = \"ABCESFCSADEE\";\n        String s = \"ABCCED\";\n\n        char[] matrix = m.toCharArray();\n        char[] str = s.toCharArray();\n\n        System.out.println(hasPath(matrix, 3, 4, str));\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_13_MovingCount.java",
    "content": "package com.ex.offer;\n\npublic class Ex_13_MovingCount {\n\n    public int movingCount(int threshold, int rows, int cols) {\n        if (threshold < 0 || rows <= 0 || cols <= 0) {\n            return 0;\n        }\n\n        boolean[] visited = new boolean[rows * cols];\n\n        int count = helper(threshold, rows, cols, 0, 0, visited);\n\n        return count;\n    }\n\n    public int helper(int threshold, int rows, int cols, int row, int col, boolean[] visited) {\n        int count = 0;\n\n        if (check(threshold, rows, cols, row, col, visited)) {\n            visited[row * cols + col] = true;\n\n            count = 1 + helper(threshold, rows, cols, row, col+1, visited)\n                    + helper(threshold, rows, cols, row+1, col, visited)\n                    + helper(threshold, rows, cols, row, col-1, visited)\n                    + helper(threshold, rows, cols, row-1, col, visited);\n        }\n\n        return count;\n    }\n\n    public boolean check(int threshold, int rows, int cols, int row, int col, boolean[] visited) {\n        if (row >= 0 && row < rows && col >= 0 && col < cols\n                && !visited[row * cols + col]\n                && getDigitSum(row) + getDigitSum(col) <= threshold) {\n            return true;\n        }\n\n        return false;\n    }\n\n    public int getDigitSum(int x) {\n        int sum = 0;\n        while (x > 0) {\n            sum += x % 10;\n            x = x / 10;\n        }\n        return sum;\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_14_MaxProductionAfterCutting.java",
    "content": "package com.ex.offer;\n\npublic class Ex_14_MaxProductionAfterCutting {\n\n    public static int maxProduction(int n) {\n        if (n == 1) {\n            return 0;\n        }\n\n        if (n == 2) {\n            return 1;\n        }\n\n        if (n == 3) {\n            return 2;\n        }\n\n        int[] products = new int[n+1];\n        products[0] = 0;\n        products[1] = 1;\n        products[2] = 2;\n        products[3] = 3;\n\n        int max = 0;\n        for (int i = 4; i <= n; i++) {\n            max = 0;\n            for (int j = 0; j <= i/2; j++) {\n                int product = products[j] * products[i-j];\n                if (product > max) {\n                    max = product;\n                }\n                products[i] = max;\n            }\n        }\n        max = products[n];\n\n        return max;\n    }\n\n    public static int maxProductionWithGreedy(int n) {\n        if (n == 1) {\n            return 0;\n        }\n\n        if (n == 2) {\n            return 1;\n        }\n\n        if (n == 3) {\n            return 2;\n        }\n\n        int timesOf3 = n/3;  // 此时 n < 3\n\n        if (n - timesOf3 * 3 == 1) {\n            timesOf3--;      // 此时 n > 5\n        }\n\n        int timesOf2 = (n - timesOf3 * 3) / 2;  // 此时 n < 2\n\n        return (int) (Math.pow(2, timesOf2) * Math.pow(3, timesOf3));\n    }\n\n    public static void main(String[] args) {\n        int n = 8;\n        System.out.println(maxProduction(n));\n        System.out.println(maxProductionWithGreedy(n));\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_15_Count1.java",
    "content": "package com.ex.offer;\n\npublic class Ex_15_Count1 {\n\n    public static int NumberOf1(int n) {\n        int count = 0;\n        int flag = 1;\n\n        while (flag != 0) {\n            if ((n & flag) != 0) {\n                count++;\n            }\n            flag = flag << 1;\n        }\n\n        return count;\n    }\n\n    public static int NumberOf1Optimal(int n) {\n        int count = 0;\n\n        while (n != 0) {\n            count++;\n            n = (n-1) & n;\n        }\n\n        return count;\n    }\n\n    public static void main(String[] args) {\n        System.out.println(NumberOf1(10));\n        System.out.println(NumberOf1Optimal(10));\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_15_CountDifferInMN.java",
    "content": "package com.ex.offer;\n\npublic class Ex_15_CountDifferInMN {\n\n    /**\n     * 计算需要改变m的二进制表示中的多少位才能得到n.\n     * @param m\n     * @param n\n     * @return\n     */\n    public static int countDiffBetweenMN(int m, int n) {\n        int x = m ^ n;   // 1. m ^ n : x中1的个数表示m和n中不同的位数个数\n        int count = 0;\n\n        while (x != 0) {\n            count++;\n            x = (x-1) & x;\n        }\n        return count;\n    }\n\n    public static void main(String[] args) {\n        int m = 10;\n        int n = 13;\n\n        System.out.println(countDiffBetweenMN(10, 13));\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_15_IsPowerOf2.java",
    "content": "package com.ex.offer;\n\npublic class Ex_15_IsPowerOf2 {\n\n    /**\n     * 判断1个数是否是2的整数次幂，例如2 4 8 ...\n     * 特点：若一个数是2的整数此幂，则这个数的二进制只有一个1\n     * (n-1) & n 将n中最右边的一个1变成了0\n     * @param n\n     * @return\n     */\n    public static boolean isPowerOf2(int n) {\n        if (n < 2) {\n            return false;\n        }\n\n        n = (n - 1) & n;\n\n        if (n == 0) {\n            return true;\n        } else {\n            return false;\n        }\n    }\n\n    public static void main(String[] args) {\n        int n = 100;\n        for (int i = 0; i <= n; i++) {\n            if (isPowerOf2(i))\n                System.out.println(i);\n        }\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_16_Power.java",
    "content": "package com.ex.offer;\n\npublic class Ex_16_Power {\n\n    /**\n     * f(n) = a ^ n\n     * 1. a != 0\n     * 2. n < 0 时， f(n) = 1 / a ^ abs(-n)\n     * 3. n > 0 时， f(n) = a ^ n\n     * @param base\n     * @param exponent\n     * @return\n     */\n    public static double Power(double base, int exponent) {\n        boolean InvalidInput_flag = false;  // 全局变量标识是否为非法输入\n\n        if (base == 0) {\n            InvalidInput_flag = true;\n            return 0.0;\n        }\n\n        int absExp = Math.abs(exponent);\n\n        double result = PowerWithUnsignedExponent(base, absExp);\n\n        if (exponent < 0) {\n            return 1 / result;\n        } else {\n            return result;\n        }\n    }\n\n    public static double PowerWithUnsignedExponent(double base, int exponent) {\n        double result = 1.0;\n\n        for (int i = 1; i <= exponent; i++) {\n            result *= base;\n        }\n\n        return result;\n    }\n\n    public static double PowerWithUnsignedExponentOptimal(double base, int exponent) {\n        if (exponent == 0) {\n            return 1;\n        }\n\n        if (exponent == 1) {\n            return base;\n        }\n\n        double result = PowerWithUnsignedExponentOptimal(base, exponent >> 1);\n\n        result *= result;\n\n        if ((exponent & 0x1) == 1) {\n            result *= base;\n        }\n\n        return result;\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_17_AddTwoBigNumber.java",
    "content": "package com.ex.offer;\n\npublic class Ex_17_AddTwoBigNumber {\n\n    /**\n     * 大数相加问题：\n     * 大数相加不能直接使用基本的int类型，因为int可以表示的整数有限，不能满足大数的要求。\n     * 可以使用字符串来表示大数，模拟大数相加的过程。\n     *\n     * 思路：\n     * 1. 反转字符串，便于从低位到高位的相加；\n     * 2. 对齐字符串，短字符串的高位用 ‘0’ 补齐，便于相加；\n     * 3. 相加。\n     * @param n1\n     * @param n2\n     * @return\n     */\n    public static String add(StringBuffer n1, StringBuffer n2) {\n        StringBuffer result = new StringBuffer();\n\n        n1.reverse();\n        n2.reverse();\n\n        int len1 = n1.length();\n        int len2 = n2.length();\n\n        int len = len1 > len2 ? len1 : len2;\n\n\n\n        boolean nOverFlow = false;\n        int nTakeOver = 0;\n\n        if (len1 < len2) {\n            for (int i = len1; i < len2; i++) {\n                n1.append('0');\n            }\n        } else {\n            for (int i = len2; i < len1; i++) {\n                n2.append('0');\n            }\n        }\n\n        for (int i = 0; i < len; i++) {\n            int nSum = Integer.parseInt(n1.charAt(i)+\"\") + (n2.charAt(i) - '0');\n            nSum += nTakeOver;\n\n            if (nSum >= 10) {\n                if (i == len - 1) {\n                    nOverFlow = true;\n                }\n\n                nTakeOver = 1;\n                result.append(nSum - 10);\n            } else {\n                nTakeOver = 0;\n                result.append(nSum);\n            }\n        }\n\n        if (nOverFlow) {\n            result.append(nTakeOver);\n        }\n\n        return result.reverse().toString();\n    }\n\n    public static void main(String[] args) {\n        StringBuffer s1 = new StringBuffer(\"-999\");\n        StringBuffer s2 = new StringBuffer(\"99\");\n        System.out.println(add(s1, s2));\n\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_17_Print1ToMaxNDigits.java",
    "content": "package com.ex.offer;\n\npublic class Ex_17_Print1ToMaxNDigits {\n\n    /**\n     * 1. 实现基本功能，但是当n很大时，count会出现int范围不够的问题，改成long，仍然会有相同的问题\n     * @param n\n     */\n    public static void print1ToMaxNDigits_1 (int n) {\n        int count = 1;\n        int i = 0;\n\n        while (i < n) {\n            count *= 10;\n            i++;\n        }\n\n\n        for (int k = 1; k < count; k++) {\n            System.out.print(k + \" \");\n            if (k % 10 == 0) {\n                System.out.println();\n            }\n        }\n\n    }\n\n    /**\n     * 2. 字符串存储数字\n     *\n     * @param n\n     */\n    public static void print1ToMaxNDigits_2 (int n) {\n        if (n <= 0) {\n            return;\n        }\n\n        StringBuffer number = new StringBuffer();\n\n        for (int i = 0; i < n; i++) {\n            number.append('0');\n        }\n\n        while (!Increment(number)) {\n            printNumber(number);\n        }\n    }\n\n    /**\n     * n位所有的十进制数：n个0~9的全排列\n     * @param n\n     */\n    public static void print1ToMaxNDigits_3 (int n) {\n        if (n <= 0) {\n            return;\n        }\n\n        StringBuffer s = new StringBuffer();\n        for (int i = 0; i < n; i++) {\n            s.append('0');\n        }\n\n        for (int i = 0; i < 10; i++) {\n            s.setCharAt(0, (char)(i+'0')); //“xx” x:0~9\n            print1ToMaxNDigits_3_Recur(s, n, 0);\n        }\n    }\n\n    /**\n     * index 数字已经确定，要确定index + 1位的数字 可选范围[0,9]\n     * @param s\n     * @param n\n     * @param index\n     */\n    public static void print1ToMaxNDigits_3_Recur(StringBuffer s, int n, int index) {\n        if (index == n-1) {\n            printNumber(s);\n            return;\n        }\n\n        for (int i = 0; i < 10; i++) {\n            s.setCharAt(index + 1, (char)(i+'0'));\n            print1ToMaxNDigits_3_Recur(s, n, index + 1);\n        }\n    }\n\n    public static boolean Increment(StringBuffer s) {\n        boolean isOverflow = false;\n        int nTakeOver = 0; //进位\n        int len = s.length();\n\n        for (int i = len-1; i >= 0; i--) {\n            int nSum = s.charAt(i) - '0' + nTakeOver;\n\n            // 若是最后1位，加1\n            if (i == len-1) {\n                nSum++;\n            }\n\n            // 若高位第一位之后的某位nSum >= 10, 则需要执行进位操作\n            // 若高位第一位nSum >= 10, 则直接返回true,说明已经执行到了最高位，且最高位进位了\n            if (nSum >= 10) {\n                if (i == 0) {\n                    isOverflow = true;\n                } else {\n                    nSum -= 10;\n                    nTakeOver = 1;\n                    s.setCharAt(i, (char)(nSum + '0'));\n                }\n            } else { // 若高位第一位之后的任何一位的nSum < 10, 则直接退出\n                s.setCharAt(i, (char)(nSum + '0'));\n                break;\n            }\n\n        }\n        return isOverflow;\n    }\n\n    // 有效位前面的0不打印\n    public static void printNumber(StringBuffer s) {\n        boolean isBeginWith0 = true;\n\n        for (int i = 0; i < s.length(); i++) {\n            if (isBeginWith0 && s.charAt(i) != '0') {\n                isBeginWith0 = false;\n            }\n\n            if (!isBeginWith0) {\n                System.out.print(s.charAt(i));\n            }\n        }\n\n        System.out.println();\n    }\n\n    public static void main(String[] args) {\n//        print1ToMaxNDigits_1(2);\n//        System.out.println();\n//        print1ToMaxNDigits_2(2);\n//        System.out.println();\n        print1ToMaxNDigits_3(2);\n\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_18_DeleteDuplicatedNode.java",
    "content": "package com.ex.offer;\n\npublic class Ex_18_DeleteDuplicatedNode {\n\n    public static ListNode deleteDuplication (ListNode pHead) {\n        ListNode first = new ListNode(-1);  // 设置一个前哨节点,不用考虑pre为空的情况\n\n        first.next = pHead;\n\n        ListNode last = first;\n        ListNode p = pHead;\n\n        while (p != null && p.next != null) {\n            if (p.val == p.next.val) {\n                int val = p.val;\n                while (p != null && p.val == val) {\n                    p = p.next;\n                }\n\n                last.next = p;\n            } else {\n                last = p;\n                p = p.next;\n            }\n        }\n\n        return first.next;\n    }\n\n    public static ListNode deleteDuplication1 (ListNode pHead) {\n        if (pHead == null || pHead.next == null) {\n            return pHead;\n        }\n\n        ListNode pre = null;\n        ListNode cur = pHead;\n\n        while (cur != null) {\n            ListNode next = cur.next;\n            boolean needDelete = false;\n\n            if (next != null && cur.val == next.val) {\n                needDelete = true;\n            }\n\n            if (!needDelete) {\n                pre = cur;\n                cur = next;\n            } else {\n                int val = cur.val;\n\n                while (cur != null && cur.val == val) {\n                    cur = cur.next;\n                }\n\n                if (pre == null) {\n                    pHead = cur;\n                } else {\n                    pre.next = cur;\n                }\n            }\n        }\n\n        return pHead;\n    }\n\n    public static void main(String[] args) {\n        ListNode head = new ListNode(1);\n        ListNode node1 = new ListNode(2);\n        ListNode node2 = new ListNode(3);\n        ListNode node3 = new ListNode(3);\n        ListNode node4 = new ListNode(4);\n        ListNode node5 = new ListNode(4);\n        ListNode node6 = new ListNode(5);\n\n\n        head.next = node1;\n        node1.next = node2;\n        node2.next = node3;\n        node3.next = node4;\n        node4.next = node5;\n        node5.next = node6;\n\n        ListNode h1 = deleteDuplication1(head);\n\n        TestUtils.printList_ListNode(h1);\n    }\n}\n\n\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_18_DeleteNodeInSList.java",
    "content": "package com.ex.offer;\n\npublic class Ex_18_DeleteNodeInSList {\n\n    public static Node deleteNode(Node head, Node toBeDeleted) {\n        if (head == null || toBeDeleted == null) {\n            return head;\n        }\n\n        // toBeDeleted is not tail\n        if (toBeDeleted.next != null) {\n            Node temp = toBeDeleted.next;\n            toBeDeleted.val = temp.val;\n            toBeDeleted.next = temp.next;\n            temp = null;\n        } else if (head == toBeDeleted){  // toBeDeleted is tail and list length = 1\n            toBeDeleted = null;\n            head = null;\n        } else { // // toBeDeleted is tail and list length != 1\n            Node pNode = head;\n            while (pNode.next != toBeDeleted) {\n                pNode = pNode.next;\n            }\n            pNode.next = null;\n        }\n\n        return head;\n    }\n\n    public static void main(String[] args) {\n        Node node1 = new Node(1);\n        node1.next = null;\n        Node head1 = deleteNode(node1, node1);  // case 2:注意 Java中是值传递\n        TestUtils.printList(head1);\n\n        Node node2 = new Node(2);\n        Node node3 = new Node(3);\n        Node node4 = new Node(4);\n        Node node5 = new Node(5);\n        node2.next = node3;\n        node3.next = node4;\n        node4.next = node5;\n        node5.next = null;\n\n        Node head2 = deleteNode(node2, node2); // case 1\n        TestUtils.printList(head2);\n\n        Node head3 = deleteNode(head2, node5); // case 3\n        TestUtils.printList(head3);\n    }\n\n}\n\n\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_19_Match.java",
    "content": "package com.ex.offer;\n\n/**\n * 当模式中的第二个字符不是“*”时：\n * 1、如果字符串第一个字符和模式中的第一个字符相匹配，那么字符串和模式都后移一个字符，然后匹配剩余的。\n * 2、如果 字符串第一个字符和模式中的第一个字符相不匹配，直接返回false。\n *\n * 而当模式中的第二个字符是“*”时：\n * 如果字符串第一个字符跟模式第一个字符不匹配，则模式后移2个字符，继续匹配。如果字符串第一个字符跟模式第一个字符匹配，可以有3种匹配方式：\n * 1、模式后移2字符，相当于x*被忽略；\n * 2、字符串后移1字符，模式后移2字符；\n * 3、字符串后移1字符，模式不变，即继续匹配字符下一位，因为*可以匹配多位；\n */\npublic class Ex_19_Match {\n\n    public boolean match(char[] str, char[] pattern) {\n        if (str == null || pattern == null) {\n            return false;\n        }\n\n        return matchCore(str, 0, pattern, 0);\n    }\n\n    private boolean matchCore(char[] str, int strIndex, char[] pattern, int patIndex) {\n        // 有效性检验： str 和 pattern都到尾，则匹配成功\n        if (strIndex == str.length && patIndex == pattern.length) {\n            return true;\n        }\n\n        // pattern 先到尾，则匹配失败\n        if (strIndex != str.length && patIndex == pattern.length) {\n            return false;\n        }\n\n        // pattern第2个是*，且str第1个和pattern第1个匹配，分3种情况；若不匹配，则pattern后移2位\n        if (patIndex + 1 < pattern.length && pattern[patIndex + 1] == '*') {\n            if (strIndex != str.length && (pattern[patIndex] == str[strIndex] || pattern[patIndex] == '.')) {\n                return matchCore(str, strIndex, pattern, patIndex+2) // 模式串后移2位，相当于忽略x*\n                        || matchCore(str, strIndex+1, pattern, patIndex+2) // 字符串，模式串都后移1位，相当于忽略*\n                        || matchCore(str, strIndex+1, pattern, patIndex); // 字符串后移1位，相当于*之前扩展了。\n            } else {\n                return matchCore(str, strIndex, pattern, patIndex+2);\n            }\n        }\n\n        // pattern第2个不是* ，且str 第1个和pattern第1个匹配，则后移一位，否则直接返回false\n        if (strIndex != str.length && (pattern[patIndex] == str[strIndex] || pattern[patIndex] == '.')) {\n            return matchCore(str, strIndex+1, pattern, patIndex+1);\n        }\n\n        return false;\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_20_IsNumber.java",
    "content": "package com.ex.offer;\n\nimport org.junit.Test;\n\npublic class Ex_20_IsNumber {\n    /**\n     * A.B[E|e]C\n     * A.B: A B任意有其一即可\n     * XEC: X C 缺一不可\n     */\n    private int index = 0;\n\n    public boolean isNumeric(char[] str) {\n        if (str == null || str.length == 0) {\n            return false;\n        }\n\n        boolean flag = scanInteger(str);\n\n        if (index < str.length && str[index] == '.') {\n            index++;\n            flag = scanUnsignedInteger(str) || flag; //若是||的话，必须先执行scan函数，否则index无法更新\n        }\n\n        if (index < str.length && (str[index] == 'E' || str[index] == 'e')) {\n            index++;\n            flag = flag && scanInteger(str);\n        }\n\n        return flag && index == str.length;\n    }\n\n    private boolean scanInteger(char[] str) {\n        if (index < str.length && (str[index] == '+' || str[index] == '-')) {\n            index++;\n        }\n\n        return scanUnsignedInteger(str);\n    }\n\n    private boolean scanUnsignedInteger(char[] str) {\n        int start = index;\n        while (index < str.length && str[index] >= '0' && str[index] <= '9') {\n            index++;\n        }\n\n        return start < index;\n    }\n\n    /**\n     以下对正则进行解释:\n     [\\\\+\\\\-]?            -> 正或负符号出现与否\n     \\\\d*                 -> 整数部分是否出现，如-.34 或 +3.34均符合\n     (\\\\.\\\\d+)?           -> 如果出现小数点，那么小数点后面必须有数字,否则一起不出现\n     ([eE][\\\\+\\\\-]?\\\\d+)? -> 如果存在指数部分，那么e或E肯定出现，+或-可以不出现，\n                             紧接着必须跟着整数；或者整个部分都不出现\n     */\n    public boolean isNumberic1(char[] str) {\n        String string = String.valueOf(str);\n        return string.matches(\"[\\\\+\\\\-]?\\\\d*(\\\\.\\\\d+)?([eE][\\\\+\\\\-]?\\\\d+)?\");\n    }\n\n    @Test\n    public void test() {\n        String str = \"123.45e+6\";\n        char[] chars = str.toCharArray();\n        System.out.println(isNumeric(chars));\n        System.out.println(isNumberic1(chars));\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_21_ReOrderArray.java",
    "content": "package com.ex.offer;\n\nimport org.junit.Test;\n\npublic class Ex_21_ReOrderArray {\n\n    public void reOrderArray(int [] array) {\n        if (array == null || array.length == 0) {\n            return;\n        }\n\n        int i = 0;\n\n        while (i < array.length) {\n            while (i < array.length && (array[i] & 1) == 1) {\n                i++;\n            }\n\n            int j = i+1;\n\n            while (j < array.length && (array[j] & 1) != 1) {\n                j++;\n            }\n\n            if (j < array.length) {\n                int tmp = array[j];\n                for (int k = j-1; k >= i; k--) {\n                    array[k+1] = array[k];\n                }\n                array[i] = tmp;\n                i++;\n            } else {\n                break;\n            }\n        }\n    }\n\n    public void reOrderArray1(int [] array) {\n        if (array == null || array.length == 0) {\n            return;\n        }\n\n        int i = 0;\n        int j = array.length-1;\n        while (i < j) {\n            while ((array[i] & 1) != 0) {\n                i++;\n            }\n\n            while ((array[j] & 1) == 0) {\n                j--;\n            }\n\n            if (i > j) break;\n\n            swap(array, i, j);\n        }\n    }\n\n    public void reOrderArray2(int [] array) {\n        if(array == null || array.length == 0) {\n            return;\n        }\n\n        for (int i = 0; i < array.length-1; i++) {\n            for (int j = 0; j < array.length-1-i; j++) {\n                if (array[j] % 2 == 0 && array[j+1] % 2 == 1) {\n                    swap(array, j, j+1);\n                }\n            }\n        }\n    }\n\n    private void swap(int[] array, int i, int j) {\n        int tmp = array[i];\n        array[i] = array[j];\n        array[j] = tmp;\n    }\n\n\n    @Test\n    public void test() {\n        int[] array = new int[] {1,2,3,4,5,6,7};\n        reOrderArray1(array);\n        TestUtils.printArray(array);\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_22_FindKthNodeToTail.java",
    "content": "package com.ex.offer;\n\nimport org.junit.Test;\n\npublic class Ex_22_FindKthNodeToTail {\n    /**\n     * 1. 空链表\n     * 2. k <= 0\n     * 3. k > len\n     * @param head\n     * @param k\n     * @return\n     */\n    public ListNode FindKthToTail(ListNode head, int k) {\n        // 1. 边界条件： head == null k <= 0\n        if (head == null || k <= 0) return null;\n\n        ListNode before = head;\n        ListNode after = head;\n\n        for (int i = 0; i < k-1; i++) {\n            before = before.next;\n        }\n        // 2. n < k: 第k个元素before已经到null，则k > n\n        if (before == null) return null;\n\n        while (before.next != null) {\n            before = before.next;\n            after = after.next;\n        }\n\n        return after;\n    }\n\n    @Test\n    public void test() {\n        ListNode head = new ListNode(1);\n        head.next = new ListNode(2);\n        head.next.next = new ListNode(3);\n        head.next.next.next = new ListNode(4);\n        head.next.next.next.next = new ListNode(5);\n        FindKthToTail(head, 5);\n    }\n\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_22_FindMedianNodeInList.java",
    "content": "package com.ex.offer;\n\nimport org.junit.Test;\n\npublic class Ex_22_FindMedianNodeInList {\n\n    public ListNode findMedian(ListNode head) {\n        if (head == null) return null;\n\n        ListNode before = head;\n        ListNode after = head;\n\n        while (before.next != null && before.next.next != null) {\n            before = before.next.next;\n            after = after.next;\n        }\n\n        return after;\n    }\n\n    @Test\n    public void test() {\n        ListNode head = new ListNode(1);\n        head.next = new ListNode(2);\n        head.next.next = new ListNode(3);\n        head.next.next.next = new ListNode(4);\n        //head.next.next.next.next = new ListNode(5);\n        System.out.println(findMedian(head).val);\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_23_EntryNodeInList.java",
    "content": "package com.ex.offer;\n\npublic class Ex_23_EntryNodeInList {\n\n    public ListNode EntryNodeOfLoop(ListNode pHead) {\n        if (pHead == null) {\n            return null;\n        }\n\n        ListNode fast = pHead;\n        ListNode slow = pHead;\n\n        while (fast.next != null && fast.next.next != null) {\n            fast = fast.next.next;\n            slow = slow.next;\n            if (fast == slow) {\n                break;\n            }\n        }\n\n        if (fast.next == null || fast.next.next == null) return null;\n\n        fast = pHead;\n        while (fast != slow) {\n            fast = fast.next;\n            slow = slow.next;\n        }\n\n        return fast;\n    }\n\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_24_ReverseSList.java",
    "content": "package com.ex.offer;\n\npublic class Ex_24_ReverseSList {\n\n    public ListNode ReverseList(ListNode head) {\n        if (head == null) return null;\n\n        ListNode pre = null;\n        ListNode cur = head;\n        ListNode next = null; // 指向剩余的需要被reverse的链表\n\n        while (cur != null) {\n            next = cur.next;  // 记录：剩余的需要被reverse的链表\n            cur.next = pre;   // 核心：cur -> pre\n            pre = cur;        // 更新pre\n            cur = next;       // 更新cur\n        }\n\n        head = pre;\n        return head;\n    }\n\n    public ListNode reverseList(ListNode head) {\n        //若是空链表或者tail节点\n        if (head == null || head.next == null) return head;\n\n        //先反转 head.next -> ...  例如： 1->2->3->4->null  1-> |2<-3<-4|\n        ListNode reverseHead = reverseList(head.next);\n        //修改head指向             null <- 1 <- |2<-3<-4|\n        head.next.next = head;\n        head.next = null;\n        return reverseHead;\n    }\n\n\n\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_25_MergeList.java",
    "content": "package com.ex.offer;\n\nimport org.junit.Test;\n\npublic class Ex_25_MergeList {\n\n    public ListNode Merge(ListNode list1, ListNode list2) {\n        if (list1 == null) return list2;\n        if (list2 == null) return list1;\n\n        ListNode head = null;\n\n        if (list1.val < list2.val) {\n            head = list1;\n            head.next = Merge(list1.next, list2);\n        } else {\n            head = list2;\n            head.next = Merge(list1, list2.next);\n        }\n\n        return head;\n    }\n\n    public ListNode Merge1(ListNode list1, ListNode list2) {\n        if (list1 == null) return list2;\n        if (list2 == null) return list1;\n\n        ListNode pre = new ListNode(-1);\n\n        ListNode node = pre;\n\n        ListNode p1 = list1;\n        ListNode p2 = list2;\n\n        while (p1 != null && p2 != null) {\n            while (p1 != null && p1.val < p2.val) {\n                node.next = new ListNode(p1.val);\n                node = node.next;\n                p1 = p1.next;\n            }\n\n            if (p1 == null) {\n                while (p2 != null) {\n                    node.next = new ListNode(p2.val);\n                    node = node.next;\n                    p2 = p2.next;\n                }\n            }\n\n            while (p2 != null && p2.val < p1.val) {\n                node.next = new ListNode(p2.val);\n                node = node.next;\n                p2 = p2.next;\n            }\n\n            if (p2 == null) {\n                while (p1 != null) {\n                    node.next = new ListNode(p1.val);\n                    node = node.next;\n                    p1 = p1.next;\n                }\n            }\n        }\n\n        return pre.next;\n    }\n\n    @Test\n    public void test() {\n        ListNode head = new ListNode(1);\n        head.next = new ListNode(3);\n        head.next.next = new ListNode(5);\n\n        ListNode head1 = new ListNode(2);\n        head1.next = new ListNode(4);\n        head1.next.next = new ListNode(6);\n        ListNode h = Merge(head, head1);\n        TestUtils.printList_ListNode(h);\n    }\n\n    @Test\n    public void test1() {\n        ListNode head = new ListNode(1);\n        head.next = new ListNode(3);\n        head.next.next = new ListNode(5);\n\n        ListNode head1 = new ListNode(2);\n        head1.next = new ListNode(4);\n        head1.next.next = new ListNode(6);\n\n        ListNode h1 = Merge1(head, head1);\n        TestUtils.printList_ListNode(h1);\n    }\n\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_26_IsSubTree.java",
    "content": "package com.ex.offer;\n\n// 此题目还可以将Tree A B 序列化，然后看B字符串是否在A字符串中，KMP算法\npublic class Ex_26_IsSubTree {\n\n    public boolean HasSubtree(TreeNode root1, TreeNode root2) {\n        if (root1 == null || root2 == null) return false;\n\n        return doesTree1HasTree2(root1, root2) || HasSubtree(root1.left, root2) || HasSubtree(root1.right, root2);\n    }\n\n    public boolean doesTree1HasTree2(TreeNode root1, TreeNode root2) {\n        if (root2 == null) {\n            return true;\n        }\n\n        if (root1 == null) {\n            return false;\n        }\n\n        if (root1.val != root2.val) {\n            return false;\n        }\n\n        return doesTree1HasTree2(root1.left, root2.left) && doesTree1HasTree2(root1.right, root2.right);\n    }\n\n\n}\n\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_27_MirrorOfTree.java",
    "content": "package com.ex.offer;\n\npublic class Ex_27_MirrorOfTree {\n\n    public void Mirror(TreeNode root) {\n        if (root == null) return;\n\n        if (root.left == null && root.right == null) return;\n\n        swapLeftAndRight(root);\n\n        Mirror(root.left);\n        Mirror(root.right);\n\n    }\n\n    public void swapLeftAndRight(TreeNode root) {\n        if (root == null) return;\n\n        TreeNode tmp = root.left;\n        root.left = root.right;\n        root.right =tmp;\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_28_SymmetricalTree.java",
    "content": "package com.ex.offer;\n\npublic class Ex_28_SymmetricalTree {\n    boolean isSymmetrical(TreeNode pRoot) {\n        if (pRoot == null) return true;\n\n        return isSymmetrical(pRoot, pRoot);\n    }\n\n    // 树的前序遍历和对称前序遍历\n    boolean isSymmetrical(TreeNode pRoot1, TreeNode pRoot2) {\n        // 递归结束条件\n        if (pRoot1 == null && pRoot2 == null) return true;\n\n        if (pRoot1 == null || pRoot2 == null) return false;\n\n        if (pRoot1.val != pRoot2.val) {\n            return false;\n        }\n\n        return isSymmetrical(pRoot1.left, pRoot2.right) && isSymmetrical(pRoot1.right, pRoot2.left);\n    }\n\n    // 树的前序遍历\n    public boolean doesTree1HasTree2(TreeNode root1, TreeNode root2) {\n        // 递归结束条件\n        if (root2 == null) {\n            return true;\n        }\n\n        if (root1 == null) {\n            return false;\n        }\n\n        if (root1.val != root2.val) {\n            return false;\n        }\n\n        return doesTree1HasTree2(root1.left, root2.left) && doesTree1HasTree2(root1.right, root2.right);\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_29_PrintMatrixWithClockWise.java",
    "content": "package com.ex.offer;\n\nimport java.util.ArrayList;\n\npublic class Ex_29_PrintMatrixWithClockWise {\n    public ArrayList<Integer> printMatrix(int [][] matrix) {\n        if (matrix == null || matrix.length <= 0) {\n            return new ArrayList<>();\n        }\n\n        ArrayList<Integer> result = new ArrayList<>();\n        ArrayList<Integer> temp = new ArrayList<>();\n\n        int r1 = 0;\n        int c1 = 0;\n        int r2 = matrix.length-1;\n        int c2 = matrix[r2].length-1;\n\n        while (r1 <= r2 && c1 <= c2) {\n            temp = printMatrixWithCircle(matrix, r1++, c1++, r2--, c2--);\n            for (Integer i : temp) {\n                result.add(i);\n            }\n        }\n        return result;\n    }\n\n    public ArrayList<Integer> printMatrixWithCircle(int[][] matrix, int r1, int c1, int r2, int c2) {\n        ArrayList<Integer> result = new ArrayList<>();\n\n        if (r1 == r2) {\n            for (int i = c1; i <= c2; i++) {\n                result.add(matrix[r1][i]);\n            }\n            return result;\n        }\n\n        if (c1 == c2) {\n            for (int i = r1; i <= r2; i++) {\n                result.add(matrix[i][c1]);\n            }\n            return result;\n        }\n\n        for (int i = c1; i < c2; i++) {\n            result.add(matrix[r1][i]);\n        }\n\n        for (int i = r1; i < r2; i++) {\n            result.add(matrix[i][c2]);\n        }\n\n        for (int i = c2; i > c1; i--)  {\n            result.add(matrix[r2][i]);\n        }\n\n        for (int i = r2; i > r1; i--) {\n            result.add(matrix[i][c1]);\n        }\n\n        return result;\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_30_StackWithMinFunction.java",
    "content": "package com.ex.offer;\n\nimport java.util.Stack;\n\npublic class Ex_30_StackWithMinFunction {\n    Stack<Integer> stack = new Stack<>();\n    Stack<Integer> help = new Stack<>();\n\n    public void push(int node) {\n        stack.push(node);\n\n        if (help.isEmpty()) {\n            help.push(node);\n        }\n\n        if (help.peek() >= node) {\n            help.push(node);\n        } else {\n            help.push(help.peek());\n        }\n    }\n\n    public void pop() {\n        if (!stack.isEmpty()) {\n            stack.pop();\n            help.pop();\n        }\n    }\n\n    public int top() {\n        if (!stack.isEmpty()) {\n            return stack.peek();\n        }\n        return -1;\n    }\n\n    public int min() {\n        if (!help.isEmpty()) {\n            return help.peek();\n        }\n        return -1;\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_31_IsPopOrder.java",
    "content": "package com.ex.offer;\n\nimport java.util.Stack;\n\npublic class Ex_31_IsPopOrder {\n    public boolean IsPopOrder(int [] pushA,int [] popA) {\n        Stack<Integer> stack = new Stack<>();\n\n        int index = 0;\n        // push:   1 2 3 4 5\n        // pop :   4 5 3 2 1\n        // stack : 1 2 3 -4-    |  <- 5 push: empty   pop: 4 5 3 2 1\n        // stack : 1 2 3  5     |       push: empty   pop: 5 3 2 1\n        for (int i = 0; i < pushA.length; i++) {\n            while (!stack.isEmpty() && popA[index] == stack.peek()) {\n                stack.pop();  // 遍历完push之前pop出去的\n                index++;\n            }\n            stack.push(pushA[i]);\n        }\n\n        // 遍历完push之后pop出去的\n        while (!stack.isEmpty() && popA[index] == stack.peek()) {\n            stack.pop();\n            index++;\n        }\n\n        return stack.isEmpty();\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_32_PrintTreeByLayer.java",
    "content": "package com.ex.offer;\n\nimport java.util.ArrayList;\nimport java.util.LinkedList;\nimport java.util.Queue;\n\npublic class Ex_32_PrintTreeByLayer {\n\n    ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) {\n        ArrayList<ArrayList<Integer>> result = new ArrayList<>();\n        ArrayList<Integer> nodes = new ArrayList<>();\n\n        int countOfNextLevel = 0;   // 统计下一层的节点数\n        int left = 1;               // 统计本层剩余的打印数\n\n        if (pRoot == null) return result;\n\n        Queue<TreeNode> queue = new LinkedList<>();\n        queue.add(pRoot);\n\n        while (!queue.isEmpty()) {\n            TreeNode x = queue.poll();\n            left--;\n            nodes.add(x.val);\n\n            if (x.left != null) {\n                queue.add(x.left);\n                countOfNextLevel++;\n            }\n\n            if (x.right != null) {\n                queue.add(x.right);\n                countOfNextLevel++;\n            }\n\n            if (left == 0) {\n                result.add(new ArrayList<>(nodes));  // 一定要注意这里，拷贝构造，而不能直接将nodes（这只是个引用）扔进去\n                nodes.clear();\n                left = countOfNextLevel;\n                countOfNextLevel = 0;\n            }\n        }\n        return result;\n    }\n\n\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_32_PrintTreeWithZhi.java",
    "content": "package com.ex.offer;\n\nimport java.util.ArrayList;\nimport java.util.Stack;\n\npublic class Ex_32_PrintTreeWithZhi {\n\n    public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {\n        ArrayList<ArrayList<Integer>> result = new ArrayList<>();\n        ArrayList<Integer> nodes = new ArrayList<>();\n\n        if (pRoot == null) return result;\n\n        Stack<TreeNode> s1 = new Stack<>(); // 奇数层 1\n        Stack<TreeNode> s2 = new Stack<>(); // 偶数层 0\n\n        int cur = 1;\n        int next = 0;\n\n        s1.add(pRoot);\n\n        while (!s1.isEmpty() || !s2.isEmpty()) {\n            TreeNode x = null;\n            if (cur == 1) {\n                x = s1.pop();\n            } else {\n                x = s2.pop();\n            }\n\n            nodes.add(x.val);\n\n            if (cur == 1) {\n                if (x.left != null) {\n                    s2.push(x.left);\n                }\n\n                if (x.right != null) {\n                    s2.push(x.right);\n                }\n\n\n            } else {\n                if (x.right != null) {\n                    s1.push(x.right);\n                }\n\n                if (x.left != null) {\n                    s1.push(x.left);\n                }\n            }\n\n            if (cur == 1 && s1.isEmpty() && !nodes.isEmpty()) {\n                result.add(new ArrayList<>(nodes));\n                nodes.clear();\n                next = 1-next;\n                cur = 1-cur;\n            }\n\n\n            if (cur == 0 && s2.isEmpty() && !nodes.isEmpty() ) {\n                result.add(new ArrayList<>(nodes));\n                nodes.clear();\n                next = 1-next;\n                cur = 1-cur;\n            }\n        }\n        return result;\n    }\n\n    // 此答案有错\n    public ArrayList<ArrayList<Integer>> Print1(TreeNode pRoot) {\n        ArrayList<ArrayList<Integer>> result = new ArrayList<>();\n        ArrayList<Integer> nodes = new ArrayList<>();\n\n        if (pRoot == null) return result;\n\n        Stack<TreeNode>[] stacks = new Stack[2];\n        int current = 0;  //奇数层\n        int next = 1;     //偶数层\n        stacks[current].push(pRoot);\n\n        while (!stacks[0].isEmpty() || !stacks[1].isEmpty()) {\n            TreeNode x = stacks[current].pop();\n            nodes.add(x.val);\n\n            if (current == 0) {\n                if (x.left != null) {\n                    stacks[next].push(x.left);\n                }\n\n                if (x.right != null) {\n                    stacks[next].push(x.right);\n                }\n            } else {\n                if (x.right != null) {\n                    stacks[next].push(x.right);\n                }\n\n                if (x.left != null) {\n                    stacks[next].push(x.left);\n                }\n            }\n\n            if (stacks[current].isEmpty()) {\n                result.add(new ArrayList<>(nodes));\n                nodes.clear();\n                current = 1 - current;\n                next = 1- next;\n\n            }\n        }\n\n        return result;\n    }\n\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_32_TraverseTreeByLayer.java",
    "content": "package com.ex.offer;\n\nimport java.util.ArrayList;\nimport java.util.LinkedList;\nimport java.util.Queue;\n\n/**\n * 注1：\n * 树的按层遍历借助于     队列\n * 树的先中后序遍历借助于 栈\n *\n * 注2：\n * 树的按层遍历本质上说就是广度优先遍历二叉树（树是图的一种特殊退化形式）\n * 那么如何广度优先遍历有向图呢？\n *\n * A:无论是广度优先遍历有向图还是二叉树，都需要用到队列。\n * 首先把起始节点（或者根节点（对树而言））放入队列\n * 然后每次从队列的头部取出一个节点，遍历这个节点之后把它能够到达的节点（或者子节点（对树而言））都一次放入队列中\n * 重复以上遍历过程，知道队列中所有的节点全部被遍历完。\n *\n */\npublic class Ex_32_TraverseTreeByLayer {\n\n    public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {\n        ArrayList<Integer> result = new ArrayList<>();\n\n        if (root == null) return result;\n\n        Queue<TreeNode> queue = new LinkedList<>();\n\n        queue.add(root);\n\n        while (!queue.isEmpty()) {\n            TreeNode temp = queue.poll();\n            result.add(temp.val);\n            if (temp.left != null) queue.add(temp.left);\n            if (temp.right != null) queue.add(temp.right);\n        }\n\n        return result;\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_33_VerifySequenceOfBST.java",
    "content": "package com.ex.offer;\n\nimport org.junit.Test;\n\npublic class Ex_33_VerifySequenceOfBST {\n    public boolean VerifySequenceOfBST(int [] sequence) {\n        if (sequence == null || sequence.length <= 0) {\n            return false;\n        }\n\n        return verifySequence(sequence, 0, sequence.length-1);\n    }\n\n    public boolean verifySequence(int[] sequence, int start, int end) {\n        if (sequence == null || start > end) {\n            return false;\n        }\n\n        // 若数组区间[start, end]元素为0则停止递归,其实可以去掉这个判断\n        if (start == end) {\n            return true;\n        }\n\n        int root = sequence[end];\n\n        // 找到左右子树的分界点[i-1,i]\n        // 小于root: [start, i-1]\n        int i = start;\n        for ( ; i < end; i++) {\n            if (sequence[i] > root) {\n                break;\n            }\n        }\n\n        // 大于root: [i, end-1]\n        int j = i;\n        for ( ; j < end; j++) {\n            if (sequence[j] < root) {\n                return false;\n            }\n        }\n\n        // 判断左子树\n        boolean left = true; // 若左子树为空，则左子树为后序遍历序列\n        if (i > start) {\n            left = verifySequence(sequence, start, i-1);\n        }\n\n        // 判断右子树\n        boolean right = true; // 若右子树为空，则右子树为后序遍历序列\n        if (i < end) {\n            right = verifySequence(sequence, i, end-1);\n        }\n\n        return left && right;\n    }\n\n    @Test\n    public void test() {\n        int[] arr = new int[] {5, 7, 6, 9, 11, 10, 8};\n        boolean result = VerifySequenceOfBST(arr);\n        System.out.println(result);\n    }\n\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_34_FindPathInBT.java",
    "content": "package com.ex.offer;\n\nimport org.junit.Test;\n\nimport java.util.ArrayList;\n\npublic class Ex_34_FindPathInBT {\n\n    public ArrayList<ArrayList<Integer>> FindPath(TreeNode root, int target) {\n        ArrayList<ArrayList<Integer>> pathList = new ArrayList<>();\n\n        if (root == null) {\n            return pathList;\n        }\n        ArrayList<Integer> path = new ArrayList<>();\n\n        findPath(root, target, path, pathList);\n\n        return pathList;\n    }\n\n    private void findPath(TreeNode root,\n                          int target,\n                          ArrayList<Integer> path,\n                          ArrayList<ArrayList<Integer>> pathList) {\n        if (root == null) return;\n\n        if (root.left == null && root.right == null) {\n            if (root.val == target) {\n                path.add(root.val);\n                pathList.add(path);\n            }\n            return;\n        }\n\n        path.add(root.val);\n        ArrayList<Integer> pathCopy = new ArrayList<>(path);\n\n        findPath(root.left, target - root.val, path, pathList);\n        findPath(root.right, target - root.val, pathCopy, pathList);\n        return;\n    }\n\n\n    @Test\n    public void test() {\n        TreeNode node1 = new TreeNode(10);\n        TreeNode node2 = new TreeNode(5);\n        TreeNode node3 = new TreeNode(12);\n        TreeNode node4 = new TreeNode(4);\n        TreeNode node5 = new TreeNode(7);\n        node1.left = node2;\n        node1.right = node3;\n        node2.left = node4;\n        node2.right = node5;\n\n        ArrayList<ArrayList<Integer>> list = FindPath(node1, 22);\n        int a = 5;\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_34_FindPathInBT_1.java",
    "content": "package com.ex.offer;\n\nimport org.junit.Test;\n\nimport java.util.ArrayList;\n\npublic class Ex_34_FindPathInBT_1 {\n    ArrayList<ArrayList<Integer>> pathList = new ArrayList<>();\n    ArrayList<Integer> path = new ArrayList<>();\n\n    public ArrayList<ArrayList<Integer>> FindPath(TreeNode root, int target) {\n        if (root == null) return pathList;\n\n        findPath(root, target);\n\n        return pathList;\n    }\n\n    private void findPath(TreeNode root, int target) {\n        path.add(root.val);\n\n        if (root.val == target && root.left == null && root.right == null) {\n            pathList.add(new ArrayList<>(path));\n        }\n\n        if (root.left != null) {\n            findPath(root.left, target - root.val);\n        }\n\n        if (root.right != null) {\n            findPath(root.right, target - root.val);\n        }\n\n        path.remove(path.size()-1);\n\n        return;\n    }\n\n\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_34_FindPathInBT_2.java",
    "content": "package com.ex.offer;\n\nimport java.util.ArrayList;\n\npublic class Ex_34_FindPathInBT_2 {\n    ArrayList<ArrayList<Integer>> pathList = new ArrayList<>();\n    ArrayList<Integer> path = new ArrayList<>();\n\n    public ArrayList<ArrayList<Integer>> FindPath(TreeNode root, int target) {\n        if (root == null) return pathList;\n\n        findPath(root, target, 0);\n\n        return pathList;\n    }\n\n    private void findPath(TreeNode root, int target, int sum) {\n        path.add(root.val);\n\n        sum += root.val;\n\n        if (sum == target && root.left == null && root.right == null) {\n            pathList.add(new ArrayList<>(path));\n        }\n\n        if (root.left != null) {\n            findPath(root.left, target, sum);\n        }\n\n        if (root.right != null) {\n            findPath(root.right, target, sum);\n        }\n\n        path.remove(path.size()-1);\n        return;\n    }\n\n\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_35_CloneList.java",
    "content": "package com.ex.offer;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class Ex_35_CloneList {\n    public RandomListNode Clone(RandomListNode pHead)\n    {\n        if (pHead == null) return pHead;\n\n        RandomListNode node = pHead;\n\n        // A - A' - B - B' - C - C' - null\n        while (node != null) {\n            RandomListNode cloneNode = new RandomListNode(node.label);\n            cloneNode.next = node.next;\n            node.next = cloneNode;\n\n            node = cloneNode.next;\n        }\n\n        // 设置Random\n        node = pHead;\n        while (node != null) {\n            RandomListNode cloneNode = node.next;\n            if (node.random != null) cloneNode.random = node.random.next;\n\n            node = cloneNode.next;\n        }\n\n        RandomListNode head = pHead.next;\n\n        // 拆分链表\n        node = pHead;\n        RandomListNode node1 = head;\n        while (node != null) {\n            node.next = node1.next;\n            node = node.next;\n            if (node == null) break;\n            node1.next = node.next;\n            node1 = node1.next;\n        }\n        return head;\n\n    }\n\n    public RandomListNode Clone1(RandomListNode pHead)\n    {\n        if (pHead == null) return pHead;\n\n        Map<RandomListNode, RandomListNode> map = new HashMap<>();\n        RandomListNode node = pHead;\n\n        while (node != null) {\n            map.put(node, new RandomListNode(node.label));\n        }\n\n        for (RandomListNode key : map.keySet()) {\n            map.get(key).next = map.get(key.next);\n            map.get(key).random = map.get(key.random);\n        }\n\n        return map.get(0);\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_36_ConvertBetweenBSTAndDList.java",
    "content": "package com.ex.offer;\n\nimport java.util.Stack;\n\npublic class Ex_36_ConvertBetweenBSTAndDList {\n    TreeNode head = null;\n    TreeNode tail = null;\n\n    public TreeNode Convert(TreeNode pRootOfTree) {\n        convert(pRootOfTree);\n        return head;\n    }\n\n    public void convert(TreeNode pRootOfTree) {\n        if (pRootOfTree == null) return;\n\n        convert(pRootOfTree.left);\n\n        if (head == null) { // 第一次，标记head节点\n            head = pRootOfTree;\n            tail = pRootOfTree;\n        } else {\n            tail.right = pRootOfTree;\n            pRootOfTree.left = tail;\n\n            tail = pRootOfTree;\n        }\n\n        convert(pRootOfTree.right);\n    }\n\n\n\n    public TreeNode ConvertIterative(TreeNode pRootOfTree) {\n        if (pRootOfTree == null) return null;\n\n        Stack<TreeNode> stack = new Stack<>();\n        TreeNode node = pRootOfTree;\n        TreeNode pre = null;\n        TreeNode head = null;\n        boolean isFirst = true;\n\n        while (node != null || !stack.isEmpty()) {\n            while (node != null) {\n                stack.push(node);\n                node = node.left;\n            }\n\n            node = stack.pop();\n\n            if (isFirst) {\n                head = node;\n                pre = head;\n                isFirst = false;\n            } else {\n                pre.right = node;\n                node.left = pre;\n                pre = node;\n            }\n            node = node.right;\n        }\n        return head;\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_37_SerializeBT.java",
    "content": "package com.ex.offer;\n\npublic class Ex_37_SerializeBT {\n    String Serialize(TreeNode root) {\n        StringBuilder sb = new StringBuilder();\n\n        if (root == null) {\n            return sb.toString();\n        }\n\n        serialize(root, sb);\n        return sb.toString();\n    }\n\n    void serialize(TreeNode root, StringBuilder sb) {\n        if (root == null) {\n            sb.append(\"#,\");\n            return;\n        }\n\n        sb.append(root.val + \",\");\n        serialize(root.left, sb);\n        serialize(root.right, sb);\n    }\n\n    int index = -1;\n    TreeNode Deserialize(String str) {\n        if (str.length() == 0) return null;\n        String[] strs = str.split(\",\");\n        return Deserialize(strs);\n    }\n\n    TreeNode Deserialize(String[] strs) {\n        index++; // 遍历strs,待返回root时，遍历结束\n        TreeNode node = null;\n        if (!strs[index].equals(\"#\")) {\n            node = new TreeNode(Integer.parseInt(strs[index]));\n            node.left = Deserialize(strs);\n            node.right = Deserialize(strs);\n        }\n        return node;\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_38_EightQueen.java",
    "content": "package com.ex.offer;\n\nimport org.junit.Test;\n\n// 8皇后问题与回溯法：https://www.cnblogs.com/bigmoyan/p/4521683.html\n//\n// 回溯法\n// 引例：设想将你放在迷宫之中，要想走出迷宫，最直接的办法是什么？试！先选择一条路开始走，\n// 走不通就退回去尝试别的路，走不通接着回退，直到走通为止。\n// 本质: 暴力破解。只不过是在暴力破解之前，利用了一些条件减少了暴力破解的一些步骤。\n\npublic class Ex_38_EightQueen {\n\n    private static final int QUEEN_NUMBER = 8;      // 皇后个数\n    private int[] columns = new int[QUEEN_NUMBER];  // 每个皇后存储的列 (row, col), row天然不相等\n    private int total = 0;\n\n    public int solution() {\n        queen(0);\n        return total;\n    }\n\n    private void queen(int row) {\n        if (row == QUEEN_NUMBER) {\n            total++;\n        } else {\n            for (int col = 0; col != QUEEN_NUMBER; col++) {\n                columns[row] = col;\n                if (isPut(row)) {\n                    queen(row+1);\n                }\n            }\n        }\n    }\n\n    private boolean isPut(int row) {\n         for (int i = 0; i != row; i++) {\n             if (columns[row] == columns[i] || row - i == Math.abs(columns[row]-columns[i])) {\n                 return false;\n             }\n         }\n         return true;\n    }\n\n    @Test\n    public void test() {\n        System.out.println(solution()); //92\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_38_StringCombination.java",
    "content": "package com.ex.offer;\n\nimport org.junit.Test;\n\nimport java.util.ArrayList;\n\npublic class Ex_38_StringCombination {\n    public ArrayList<String> Combination(String str) {\n        ArrayList<String> res = new ArrayList<>();\n        if (str == null || str.length() <= 0) return res;\n\n        combination(str.toCharArray(), 0, res);\n        return res;\n    }\n\n    private void combination(char[] chars, int startIndex, ArrayList<String> res) {\n        if (startIndex == chars.length) {\n            StringBuilder sb = new StringBuilder();\n            for (char c : chars) {\n                if (c != 0) sb.append(c);\n            }\n\n            res.add(sb.toString());\n            return;\n        }\n\n        combination(chars, startIndex+1, res);\n        char temp = chars[startIndex];\n        chars[startIndex] = 0;\n        combination(chars, startIndex+1, res);\n        chars[startIndex] = temp;\n    }\n\n    @Test\n    public void test() {\n        ArrayList<String> res = Combination(new String(\"abc\"));\n        for (String str : res) {\n            System.out.println(str);\n        }\n    }\n\n\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_38_StringPermutation.java",
    "content": "package com.ex.offer;\n\nimport java.util.ArrayList;\nimport java.util.Collections;\n\npublic class Ex_38_StringPermutation {\n    public ArrayList<String> Permutation(String str) {\n        ArrayList<String> res = new ArrayList<>();\n        if (str == null || str.length() <= 0) return res;\n\n        permutation(str.toCharArray(), 0, res);\n        Collections.sort(res);\n        return res;\n    }\n\n    private void permutation(char[] chars, int startIndex, ArrayList<String> res) {\n        if (startIndex == chars.length-1) {\n            String str = String.valueOf(chars);\n            if (!res.contains(str)) {\n                res.add(str);\n            }\n        } else {\n            // 第一个字符与后面所有字符逐个交换：a|bcde   b|acde  c|bade d|bcae e|bcda\n            // 第一个字符固定，第二个字符和后面所有字符逐个交换：a || b|cde c|bde d|cbe e|cdb\n            for (int i = startIndex; i < chars.length; i++) {\n                swap(chars, startIndex, i);\n                permutation(chars, startIndex + 1, res);  // a || b|cde c|bde d|cbe e|cdb\n                swap(chars, startIndex, i);\n            }\n        }\n    }\n\n    private void swap(char[] chars, int i, int j) {\n        char tmp = chars[i];\n        chars[i] = chars[j];\n        chars[j] = tmp;\n    }\n\n\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_39_KthSmallestNumInArrayWithoutSort.java",
    "content": "package com.ex.offer;\n\npublic class Ex_39_KthSmallestNumInArrayWithoutSort {\n\n    /**\n     * 找到第K个最小的数字，同时RAND-PARTITION之后，K个数(包含第K个数)左侧为最小的K个数\n     * @param arr\n     * @param K\n     * @return\n     */\n    public static int kthNumIte(int[] arr, int K) {\n        if (arr == null || arr.length < K || K <= 0 || arr.length <= 0) {\n            return -1;\n        }\n\n        int low = 0;\n        int high = arr.length - 1;\n        int p = partition(arr, low, high);\n\n        while (p != K-1) {\n            if (p > K - 1) {\n                p = partition(arr, low, p-1);\n            } else {\n                p = partition(arr, p+1, high);\n            }\n        }\n\n        return arr[p];\n    }\n\n\n    public static int kthNum(int[] arr, int K) {\n        if (arr == null || arr.length < K || K <= 0 || arr.length <= 0) {\n            return -1;\n        }\n\n        return kthNum(arr, K, 0, arr.length-1);\n    }\n\n    /**\n     * RAND-SELECT(array, K, low, high)\n     * 1. if low == high, RETURN array[low]   // 递归结束的条件\n     * 2. p = RAND-PARTITION(arr, low, high)  // [low, high]中，pivot元素在数组中的index\n     * 3. count = p - low + 1;                // [low, high]中, pivot元素是第几个元素\n     * 4. if count > k       RETURN RAND-SELECT(array, K, low, p-1)\n     *    else if count < K  RETURN RAND-SELECT(array, K-count, p+1, high)\n     *    else               RETURN arr[p];\n     *\n     * @param arr\n     * @param K\n     * @param low\n     * @param high\n     * @return\n     */\n    public static int kthNum(int[] arr, int K, int low, int high) {\n        if (low == high) {\n            return arr[low];\n        } else{\n            int p = partition(arr, low, high);\n            int count = p - low + 1;  // count:从low开始第count个值\n\n            if (count > K) {\n                return kthNum(arr, K, low, p-1);\n            } else if (count < K) {\n                return kthNum(arr, K-count, p+1, high);\n            } else {\n                return arr[p];\n            }\n        }\n\n    }\n\n    /**\n     * RAND-PARTITION(array, low, high)\n     *\n     * 1. 随机挑选一个元素作为主元pivot，将该元素换到low位置；\n     * 2. 指定2个指针:\n     * 2.1 i:指向low,若arr[i] < pivot,则i++;\n     * 2.2 j:指向high,若arr[j] > pivot, 则j--;\n     * 不断重复2.1 2.2,此时，arr[i] >= pivot, arr[j] <= pivot, 交换arr[i], arr[j]\n     * 3. 重复步骤2，直到 i < j条件不满足\n     * 4. 交换 arr[low] 和 arr[j]\n     *   low       i  j\n     * [pivot,  <= x, >= x]\n     *\n     * @param arr\n     * @param low\n     * @param high\n     * @return\n     */\n    public static int partition(int[] arr, int low, int high) {\n        if (low == high) {\n            return low;\n        }\n\n        int pIndex = low + (int)(Math.random() * (high - low));\n        swap(arr, pIndex, low);\n\n        int pivot = arr[low];  // pivot始终选择第一个元素\n\n        int i = low;\n        int j = high + 1;\n\n        while (i < j) {\n            while (arr[++i] < pivot) {\n                if (i == high) {\n                    break;\n                }\n            }\n\n            while (arr[--j] > pivot) {\n                if (j == low) {\n                    break;\n                }\n            }\n\n            if (i > j) {\n                break;\n            }\n\n            swap(arr, i, j);\n        }\n\n        swap(arr, j, low);\n\n        return j;\n    }\n\n    public static void swap(int[] arr, int i, int j) {\n        int tmp = arr[i];\n        arr[i] = arr[j];\n        arr[j] = tmp;\n    }\n\n    public static void main(String[] args) {\n        int[] arr = new int[] {6, 4, 7, -2, 9, 6, 8, 2, -5, 5};\n//        ArrayUtils.printArray(arr);\n//        int p = partition(arr, 0, arr.length-1);\n//        System.out.println(p + \" : \" + arr[p]);\n//        ArrayUtils.printArray(arr);\n\n        System.out.println(\"======================================\");\n        TestUtils.printArray(arr);\n        for (int K = 1; K <= arr.length; K++) {\n            int kth = kthNum(arr, K);\n            System.out.print(kth + \" \");\n        }\n\n        int kth = kthNum(arr, 0);\n        System.out.print(kth + \" \");\n        System.out.println();\n\n        System.out.println(\"======================================\");\n        int[] arr1 = new int[] {6, 4, 7, -2, 9, 6, 8, 2, -5, 5};\n        TestUtils.printArray(arr1);\n        for (int K = 1; K <= arr1.length; K++) {\n            int kth1 = kthNumIte(arr1, K);\n            System.out.print(kth1 + \" \");\n        }\n\n        int kth1 = kthNumIte(arr1, 0);\n        System.out.print(kth1 + \" \");\n        System.out.println();\n\n        System.out.println(\"======================================\");\n        int[] arr2 = new int[] {6, 4, 7, -2, 9, 6, 8, 2, -5, 5};\n        int K = 5;\n        TestUtils.printArray(arr2);\n        int kth2 = kthNumIte(arr2, K);\n        System.out.println(K + \":\" + arr2[K-1]);\n        TestUtils.printArray(arr2);\n\n    }\n\n\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_39_MoreThanHalfNum.java",
    "content": "package com.ex.offer;\n\npublic class Ex_39_MoreThanHalfNum {\n\n    public static int moreThanHalfNum(int[] array) {\n        if (array == null || array.length <= 0) {\n            return 0;\n        }\n\n        if (array.length == 1) {\n            return array[0];\n        }\n\n        int low = 0;\n        int high = array.length-1;\n        int mid = low + (high - low) / 2;\n\n        int p = partition(array, low, high);\n\n        while (p != mid) {\n            if (p < mid) {\n                p = partition(array, p+1, high);\n            } else {\n                p = partition(array, low, p-1);\n            }\n        }\n        int result = array[mid];\n\n        if (!checkMoreThanHalf(array, result)) {\n            result = 0;\n        }\n\n        return result;\n    }\n\n    public static boolean checkMoreThanHalf(int[] arr, int result) {\n        int times = 0;\n\n        for (int i = 0; i < arr.length; i++) {\n            if (arr[i] == result) {\n                times++;\n            }\n        }\n\n        if (times * 2 <= arr.length) {\n            return false;\n        }\n\n        return true;\n    }\n\n    public static int partition(int[] arr, int low, int high) {\n        if (low == high) {\n            return low;\n        }\n        int pIndex = low + (int) (Math.random() *(high - low));\n        swap(arr, low, pIndex);\n\n        int pivot = arr[low];\n\n        int i = low;\n        int j = high + 1;\n\n        while (i < j) {\n            while (arr[++i] < pivot) {\n                if (i == high) {\n                    break;\n                }\n            }\n\n            while (arr[--j] > pivot) {\n                if (j == low) {\n                    break;\n                }\n            }\n\n            if (i > j) {\n                break;\n            }\n\n            swap(arr, i, j);\n        }\n        swap(arr, j, low);\n\n        return j;\n    }\n\n    public static void swap(int[] arr, int i, int j) {\n        int tmp = arr[i];\n        arr[i] = arr[j];\n        arr[j] = tmp;\n    }\n\n    public static int moreThanHalfNumWithoutChangeArray(int[] array) {\n        if (array == null || array.length <= 0) {\n            return 0;\n        }\n\n        int result = array[0];\n        int times = 1;\n\n        for (int i = 1; i < array.length; i++) {\n            if (times == 0) {\n                result = array[i];\n                times = 1;\n            } else if (array[i] == result) {\n                times++;\n            } else {\n                times--;\n            }\n        }\n\n        if (!checkMoreThanHalf(array, result)) {\n            result = 0;\n        }\n\n        return result;\n    }\n\n    public static void main(String[] args) {\n        int[] arr = new int[]{1,2,3,2,2,2,5,4,2};\n        System.out.println(moreThanHalfNumWithoutChangeArray(arr));\n        System.out.println(moreThanHalfNumWithoutChangeArray(new int[]{1}));\n        System.out.println(\"=============================\");\n        TestUtils.printArray(arr);\n        System.out.println(moreThanHalfNum(arr));\n        TestUtils.printArray(arr);\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_40_GetLeastKNumbers.java",
    "content": "package com.ex.offer;\n\nimport java.util.ArrayList;\n\npublic class Ex_40_GetLeastKNumbers {\n\n    public static ArrayList<Integer> getLeastKNumbers(int[] input, int k) {\n        if (input == null || k <= 0 || input.length < k || input.length <= 0) {\n            return null;\n        }\n\n        int low = 0;\n        int high = input.length - 1;\n        int p = partition(input, low, high);\n\n        while (p != k-1) {\n            if (p > k-1) {\n                p = partition(input, low, p-1);\n            } else {\n                p = partition(input, p+1, high);\n            }\n        }\n        ArrayList<Integer> res = new ArrayList<>();\n        for (int i = 0; i < k; i++) {\n            res.add(input[i]);\n        }\n        return res;\n    }\n\n    // 找到第k小的数（那其左边就是比arr[k]小的k个数）\n    public static int kthNum(int[] input, int k) {\n        if (input == null || k <= 0 || input.length < k || input.length <= 0) {\n            return -1;\n        }\n\n        int low = 0;\n        int high = input.length - 1;\n        int p = partition(input, low, high);\n\n        while (p != k-1) {\n            if (p > k-1) {\n                p = partition(input, low, p-1);\n            } else {\n                p = partition(input, p+1, high);\n            }\n        }\n\n        return input[p];\n    }\n\n    public static int partition(int[] arr, int low, int high) {\n        if (low == high) {\n            return low;\n        }\n\n        int pivotIndex = low + (int) (Math.random() * (high - low));\n        swap(arr, low, pivotIndex);\n\n        int pivot = arr[low];\n        int i = low;\n        int j = high + 1;\n        while (i < j) {\n            while (arr[++i] < pivot) {\n                if (i == high) break;\n            }\n\n            while (arr[--j] > pivot) {\n                if (j == low) break;\n            }\n\n            if (i > j) break;\n\n            swap(arr, i, j);\n        }\n\n        swap(arr, j, low);\n\n        return j;\n    }\n\n    public static void swap(int[] arr, int i, int j) {\n        int tmp = arr[i];\n        arr[i] = arr[j];\n        arr[j]= tmp;\n    }\n\n    public static void main(String[] args) {\n        int[] arr = new int[] {4,5,1,6,2,7,3,8};\n        for (int i : getLeastKNumbers(arr, 8)) {\n            System.out.println(i);\n        }\n\n        System.out.println(kthNum(arr, 5));\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_41_MedianInDataFlow.java",
    "content": "package com.ex.offer;\n\nimport java.util.Comparator;\nimport java.util.PriorityQueue;\n\npublic class Ex_41_MedianInDataFlow {\n\n    private PriorityQueue<Integer> maxHeap = new PriorityQueue<>(new MaxHeapComparator());\n    private PriorityQueue<Integer> minHeap = new PriorityQueue<>(new MinHeapComparator());\n\n    public void Insert(Integer num) {\n        if (this.maxHeap.isEmpty()) {\n            this.maxHeap.add(num);\n            return;\n        }\n\n        if (num <= this.maxHeap.peek()) {\n            this.maxHeap.add(num);\n        } else {\n            if (this.minHeap.isEmpty()) {\n                this.minHeap.add(num);\n                return;\n            }\n\n            if (num >= this.minHeap.peek()) {\n                this.minHeap.add(num);\n            } else {\n                this.maxHeap.add(num);\n            }\n        }\n\n        modifyTwoHeapSize();\n    }\n\n    public Double GetMedian() {\n        int maxHeapSize = this.maxHeap.size();\n        int minHeapSize = this.minHeap.size();\n\n        // 若MaxHeap或者minHeap为空，则直接return null\n        if (maxHeapSize + minHeapSize == 0) {\n            return null;\n        }\n\n        Integer max = this.maxHeap.peek();\n        Integer min = this.minHeap.peek();\n\n        if (maxHeapSize == minHeapSize) {\n            return (max + min) / 2.0;\n        }\n\n        return 1.0 * (maxHeapSize > minHeapSize ? max : min);\n    }\n\n    private void modifyTwoHeapSize() {\n        if (this.maxHeap.size() == this.minHeap.size() + 2) {\n            this.minHeap.add(this.maxHeap.poll());\n        }\n\n        if (this.minHeap.size() == this.maxHeap.size() + 2) {\n            this.maxHeap.add(this.minHeap.poll());\n        }\n    }\n\n    private static class MinHeapComparator implements Comparator<Integer> {\n\n        @Override\n        public int compare(Integer o1, Integer o2) {\n            if (o1 > o2) {\n                return 1;\n            } else {\n                return -1;\n            }\n        }\n    }\n\n    private static class MaxHeapComparator implements Comparator<Integer> {\n        @Override\n        public int compare(Integer o1, Integer o2) {\n            return o2 > o1 ? 1 : -1;\n        }\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_42_MaxSumOfSubArray.java",
    "content": "package com.ex.offer;\n\n// 此题目类似于：Ex_63_MaxProfits\npublic class Ex_42_MaxSumOfSubArray {\n    public int FindGreatestSumOfSubArray(int[] array) {\n        if (array == null || array.length < 1) {\n            return 0;\n        }\n\n        int max = Integer.MIN_VALUE;\n        int curSum = 0;\n\n        for (int i = 0; i < array.length; i++) {\n            curSum += array[i];\n            max = Math.max(max, curSum);\n            curSum = curSum < 0 ? 0 : curSum;\n        }\n\n        return max;\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_43_NumberOf1Between1AndN.java",
    "content": "package com.ex.offer;\n\n//https://www.cnblogs.com/xuanxufeng/p/6854105.html\npublic class Ex_43_NumberOf1Between1AndN {\n    public int NumberOf1Between1AndN_Solution1(int n) {\n        if (n < 1) {\n            return 0;\n        }\n\n        int count = 0;\n        for (int i = 1; i <= n; i++) {\n            count += numberOf1(i);\n        }\n\n        return count;\n    }\n\n    private int numberOf1(int num) {\n        int count = 0;\n        while (num != 0) {\n            if (num % 10 == 1) {\n                count++;\n            }\n            num = num / 10;\n        }\n\n        return count;\n    }\n\n    public int NumberOf1Between1AndN_Solution(int n) {\n        int ones = 0; // ones:1的个数\n        // m:分别指的是个位，十位，百位...，即：10 100 1000 ... m是在以10倍增长，因此可能超过int型，变成long\n        // 分别按照个位十位百位统计各个位子上的个数\n        for (long m = 1; m <= n; m *= 10) {\n            //a = n / m;   // n的高位\n            //b = n % m;   // n的低位\n            ones += (n/m + 8) / 10 * m + (n/m % 10 == 1 ? n%m + 1 : 0);\n        }\n\n        return ones;\n    }\n\n\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_44_ANumInArray.java",
    "content": "package com.ex.offer;\n\nimport org.junit.Test;\n\npublic class Ex_44_ANumInArray {\n    public int digitAt(int index) {\n        if (index < 0) {\n            return -1;\n        }\n\n        int digits = 1;\n\n        while (true) {\n            int numbers = countNumbersOf(digits);\n            if (index < numbers * digits) {\n                return digitAt(index, digits);\n            }\n\n            index -= numbers * digits;\n            digits++;\n        }\n    }\n\n    private int countNumbersOf(int digits) {\n        if (digits == 1) {\n            return 10;\n        }\n\n        return 9 * (int)Math.pow(10, digits-1);\n    }\n\n    private int digitAt(int index, int digits) {\n        int startNumber = digits == 1 ? 0 : (int)Math.pow(10, digits-1);\n        int endNumber = startNumber + index / digits;\n        index = digits - index % digits;\n        for (int i = 1; i < index; i++) {\n            endNumber /= 10;\n        }\n\n        return endNumber % 10;\n    }\n\n    @Test\n    public void test() {\n        System.out.println(digitAt(1001));\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_45_MinNumByConcatArray.java",
    "content": "package com.ex.offer;\n\nimport java.util.Arrays;\nimport java.util.Comparator;\n\n// 最小字典序问题\npublic class Ex_45_MinNumByConcatArray {\n    public String PrintMinNumber(int [] numbers) {\n        if(numbers == null || numbers.length <= 0) {\n            return \"\";\n        }\n\n        String[] strs = new String[numbers.length];\n        for (int i = 0; i < numbers.length; i++) {\n            strs[i] = String.valueOf(numbers[i]);\n        }\n\n        Arrays.sort(strs, new StrComparator());\n\n        String res = \"\";\n        for (String str : strs) {\n             res += str;\n        }\n\n        return res;\n    }\n\n    private static class StrComparator implements Comparator<String> {\n\n        @Override\n        public int compare(String o1, String o2) {\n            return (o1+o2).compareTo(o2+o1);\n        }\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_46_ConvertStringToIP.java",
    "content": "package com.ex.offer;\n\n/**\n * 附加题目\n *\n * problem 5: [String][递归][动态规划]\n *\n * 给定一个由数字组成的字符串， 请返回能返回多少种合法的ipv4组合。\n *\n * 知识点：\n * IPv4: 点分十进制\n * 1. x.x.x.x: 4 parts\n * 2. 0 <= x <= 255\n * 3. x不能有0a这种形式\n */\npublic class Ex_46_ConvertStringToIP {\n\n    public static int convertStringToIp1(String str) {\n        if (str == null || str.length() < 4 || str.length() > 12) {\n            return 0;\n        }\n\n        char[] chars = str.toCharArray();\n        return process1(chars, 0, 0);\n    }\n\n    /**\n     *\n     * @param chars\n     * @param i       0~i-1已经形成合法的IPv4的部分，考察i~N-1能组合出多少种\n     * @param parts   0~i-1已经形成合法IPv4的部分的部分数\n     * @return\n     */\n    public static int process1(char[] chars, int i, int parts) {\n//        if (i > chars.length || parts > 4) {\n//            return 0;\n//        }\n\n        if (i == chars.length) {\n            return parts == 4 ? 1 : 0;\n        }\n\n        int res = 0;\n\n        res += process1(chars, i+1, parts+1);\n\n        if (chars[i] == '0') {\n            return res;\n        }\n\n        if (i + 2 <= chars.length) {\n            res += process1(chars, i+2, parts+1);\n        }\n\n        if (i + 3 <= chars.length) {\n            int sum = (chars[i] - '0') * 100 + (chars[i+1] - '0') * 10 + (chars[i+2] - '0');\n            if (sum <= 255) {\n                return res + process1(chars, i+3, parts + 1);\n            }\n        }\n\n        return res;\n    }\n\n    public static int convertStringToIp2(String str) {\n        if (str == null || str.length() < 4 || str.length() > 12) {\n            return 0;\n        }\n\n        char[] chars = str.toCharArray();\n        int[][] dp = new int[chars.length+1][6];\n\n        dp[chars.length][4] = 1;\n\n        for (int i = dp.length-2; i >= 0; i--) {\n            for (int j = dp[i].length - 2; j >= 0; j--) {\n\n                 dp[i][j] = dp[i+1][j+1];\n\n                if (chars[i] != '0') {\n                    if (i+2 < dp.length) {\n                        dp[i][j] = dp[i][j] + dp[i+2][j+1];\n                    }\n\n                    if (i+3 < dp.length) {\n                        int sum = (chars[i] - '0') * 100 + (chars[i+1] - '0') * 10 + (chars[i+2] - '0');\n                        if (sum < 256) {\n                            dp[i][j] = dp[i][j] + dp[i + 3][j + 1];\n                        }\n                    }\n                }\n            }\n        }\n        return dp[0][0];\n    }\n\n    public static String getRandomNumberString() {\n        char[] chas = new char[(int) (Math.random() * 10) + 3];\n        for (int i = 0; i < chas.length; i++) {\n            chas[i] = (char) (48 + (int) (Math.random() * 10));\n        }\n        return String.valueOf(chas);\n    }\n\n    public static void main(String[] args) {\n        int testTime = 3000000;\n        boolean hasErr = false;\n        for (int i = 0; i < testTime; i++) {\n            String test = getRandomNumberString();\n            if (convertStringToIp1(test) != convertStringToIp2(test)) {\n                hasErr = true;\n            }\n        }\n        if (hasErr) {\n            System.out.println(\"233333\");\n        } else {\n            System.out.println(\"666666\");\n        }\n\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_46_TranslationFromIntToString.java",
    "content": "package com.ex.offer;\n\nimport org.junit.Test;\n\n/**\n * String -> Another String\n */\npublic class Ex_46_TranslationFromIntToString {\n    // 动态规划：从下而上（从后往前）\n    public int translation(int num) {\n        if (num < 0) {\n            return -1;\n        }\n\n        String str = String.valueOf(num);\n        int len = str.length();\n        int counts[] = new int[len];\n\n        counts[len-1] = 1;\n\n        for (int i = len-2; i>=0; i--) {\n            int count = 0;\n            count = counts[i+1];\n\n            int d1 = str.charAt(i) - '0';\n            int d2 = str.charAt(i+1) - '0';\n            int convertedNum = d1 * 10 + d2;\n            if (convertedNum >= 10 && convertedNum <=25) {\n                if (i < len-2) {\n                    count += counts[i+2];\n                } else {\n                    count += 1;\n                }\n            }\n            counts[i] = count;\n        }\n\n        return counts[0];\n    }\n\n    // 递归：自上而下（从前到后）\n    public int translation1(int num) {\n        if (num < 0) {\n            return -1;\n        }\n\n        String str = String.valueOf(num);\n        char[] chars = str.toCharArray();\n\n        return translationCore(chars, 0);\n    }\n\n    private int translationCore(char[] chars, int start) {\n        if (start == chars.length) {\n            return 1;\n        }\n\n        int res = 0;\n\n        res += translationCore(chars, start + 1);\n\n        if (chars[start] == '0') {\n            return res;\n        }\n\n        if (start + 1 < chars.length) {\n            int sum = (chars[start] - '0') * 10 + (chars[start+1] - '0');\n            if (sum < 26) {\n                res += translationCore(chars, start + 2);\n            }\n        }\n\n        return res;\n    }\n\n    @Test\n    public void test() {\n        System.out.println(translation(1234));\n        System.out.println(translation(12258));\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_47_MaxGiftValue.java",
    "content": "package com.ex.offer;\n\nimport org.junit.Test;\n\npublic class Ex_47_MaxGiftValue {\n    public int getMaxValue(int[][] matrix) {\n        if (matrix == null || matrix.length <= 0 || matrix[0].length <= 0) {\n            return -1;\n        }\n\n        int rowSize = matrix.length;\n        int colSize = matrix[0].length;\n        int[][] result = new int[rowSize][colSize];\n\n        for (int i = 0; i < rowSize; i++) {\n            for (int j = 0; j < colSize; j++) {\n                int left = 0;\n                int up = 0;\n                if (i > 0) {\n                    left = result[i-1][j];\n                }\n                if (j > 0) {\n                    up = result[i][j-1];\n                }\n\n                result[i][j] = Math.max(left, up) + matrix[i][j];\n            }\n        }\n\n        return result[rowSize-1][colSize-1];\n    }\n\n    public int getMaxValue1(int[][] matrix) {\n        if (matrix == null || matrix.length <= 0 || matrix[0].length <= 0) {\n            return -1;\n        }\n\n        return process(matrix, 0, 0);\n    }\n\n    private int process(int[][] matrix, int startRow, int startCol) {\n        int rowSize = matrix.length;\n        int colSize = matrix[0].length;\n        int curValue = matrix[startRow][startCol];\n\n        if (startRow == rowSize && startCol == colSize) {\n            return matrix[startRow][startCol];\n        }\n\n\n        int down = 0;\n        int right = 0;\n        if (startRow + 1 < rowSize) {\n            down = process(matrix, startRow + 1, startCol);\n        }\n\n        if (startCol + 1 < colSize) {\n            right = process(matrix, startRow, startCol + 1);\n        }\n\n        return  curValue + Math.max(down, right);\n    }\n\n    @Test\n    public void test() {\n        int[][] matrix = new int[][] {\n                {1 , 10, 3 , 8 },\n                {12, 2 , 9 , 6 },\n                {5 , 7 , 4 , 11},\n                {3,  7 , 16, 5 }\n        };\n        System.out.println(getMaxValue(matrix));\n        System.out.println(getMaxValue1(matrix));\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_48_LongestSubStringWithDuplication.java",
    "content": "package com.ex.offer;\n\nimport org.junit.Test;\n\n// 这个题目和Ex_42_MaxSumOfSubArray类似\npublic class Ex_48_LongestSubStringWithDuplication {\n    public int longestSubString(String str) {\n        if (str == null || str.length() < 1) {\n            return 0;\n        }\n\n        int curLen = 0;\n        int maxLen = 0;\n\n        // 注意这里利用一个int[]记录了每个字符上次出现的位置，这样就可以计算出每个位置和他上次出现位置的距离\n        // 注意其下标为：char - 'a'\n        int[] lastPositions = new int[26];  // 某个字符上一次出现的索引，从未出现为-1；\n\n        for (int i = 0; i < 26; i++) {\n            lastPositions[i] = -1;\n        }\n\n        for (int i = 0; i < str.length(); i++) {\n            int lastIndex = lastPositions[str.charAt(i) - 'a'];\n            int distance = i - lastIndex;\n            if (lastIndex < -1 || distance > curLen) {\n                curLen++;\n            } else {\n                curLen = distance;\n            }\n\n            if (curLen > maxLen) maxLen = curLen;\n\n            lastPositions[str.charAt(i) - 'a'] = i; // 更新最后出现位置\n        }\n\n        return Math.max(maxLen, curLen);\n    }\n\n    @Test\n    public void test() {\n        String str = \"arabcacfr\";\n        System.out.println(longestSubString(str));\n    }\n\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_49_UglyNumber.java",
    "content": "package com.ex.offer;\n\nimport org.junit.Test;\n\npublic class Ex_49_UglyNumber {\n    // 保存所有丑数，同时只检查丑数，不检查非丑数\n    public int getUglyNumber(int index) {\n        if (index <= 0) {\n            return 0;\n        }\n\n        int[] uglyNumbers = new int[index];\n        uglyNumbers[0] = 1;\n        int nextIndex = 1;\n        int indexOf2 = 0; // nextIndex之前（包括）最小的索引（*2得到的丑数）\n        int indexOf3 = 0;\n        int indexOf5 = 0;\n\n        while (nextIndex < index) {\n            int nextUgly = min(uglyNumbers[indexOf2] * 2, uglyNumbers[indexOf3] * 3, uglyNumbers[indexOf5] * 5);\n            uglyNumbers[nextIndex] = nextUgly;\n\n            while (uglyNumbers[indexOf2] * 2 <= nextUgly) {\n                indexOf2++;\n            }\n\n            while (uglyNumbers[indexOf3] * 3 <= nextUgly) {\n                indexOf3++;\n            }\n\n            while (uglyNumbers[indexOf5] * 5 <= nextUgly) {\n                indexOf5++;\n            }\n\n            nextIndex++;\n        }\n\n        return uglyNumbers[index-1];\n    }\n\n    private int min(int x, int y, int z) {\n        int min = x < y ? x : y;\n\n        return min < z ? min : z;\n    }\n    // sol 1: 暴力解法\n    public int getUglyNumber1(int index) {\n        if (index <= 0) {\n            return -1;\n        }\n\n        int number = 0;\n        int uglyCount = 0;\n\n        while (uglyCount < index) {\n            number++;\n            if (isUgly(number)) {\n                uglyCount++;\n            }\n        }\n\n        return number;\n    }\n    // 丑数的性质：\n    // 若一个数仅能被2, 3, 5整除，那么除去所有的2 3 5 因子，之后应该是1\n    // 若一个数是丑数，则这个数的2，3， 5倍都是丑数。\n    public boolean isUgly(int number) {\n        if (number == 1) {\n            return true;\n        }\n\n        while (number % 2 == 0) {\n            number /= 2;\n        }\n\n        while (number % 3 == 0) {\n            number /= 3;\n        }\n\n        while (number % 5 == 0) {\n            number /= 5;\n        }\n\n        return number == 1 ? true : false;\n    }\n\n    @Test\n    public void test() {\n        int number = 14;\n        System.out.println(getUglyNumber(1500));\n        System.out.println(getUglyNumber1(1500));\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_50_FirstNotRepeatedChar.java",
    "content": "package com.ex.offer;\n\nimport java.util.HashMap;\n\npublic class Ex_50_FirstNotRepeatedChar {\n    public int FirstNotRepeatingChar(String str) {\n        if (str == null || str.length() < 1) {\n            return -1;\n        }\n\n        int[] hashTable = new int[256]; // 简单的HashTable\n\n        for (int i = 0; i < 256; i++) {\n            hashTable[i] = 0;\n        }\n\n        for (int i = 0; i < str.length(); i++) {\n            hashTable[str.charAt(i)]++;\n        }\n\n        int index = -1;\n\n        for (int i = 0; i < str.length(); i++) {\n            if (hashTable[str.charAt(i)] == 1) {\n                index = i;\n                break;\n            }\n        }\n\n        return index;\n    }\n\n\n    public int FirstNotRepeatingChar1(String str) {\n        if (str == null || str.length() < 1) {\n            return -1;\n        }\n\n        HashMap<Character, Integer> map = new HashMap<>();\n        for (int i = 0; i < str.length(); i++) {\n            if (!map.containsKey(str.charAt(i))) {\n                map.put(str.charAt(i), 1);\n            } else {\n                int count = map.get(str.charAt(i)).intValue() + 1;\n                map.put(str.charAt(i), count);\n            }\n        }\n\n        int index = 0;\n        for (int i = 0; i < str.length(); i++) {\n            if (map.get(str.charAt(i)).intValue() == 1) {\n                index = i;\n                break;\n            }\n        }\n        return index;\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_50_FirstNotRepeatedCharInDataFlow.java",
    "content": "package com.ex.offer;\n\npublic class Ex_50_FirstNotRepeatedCharInDataFlow {\n\n    private static final int TABLE_SIZE = 256;\n\n    // 保存字符在字符串中的位置\n    // -1：初始值\n    // -2：重复\n    // >= 0：表示第一次出现\n    private int[] hashTable = new int[TABLE_SIZE];\n\n    private int index = 0;\n\n    public Ex_50_FirstNotRepeatedCharInDataFlow() {\n        for (int i = 0; i < TABLE_SIZE; i++) {\n            hashTable[i] = -1;\n        }\n    }\n\n    //Insert one char from string stream\n    public void Insert(char ch)\n    {\n        if (hashTable[ch] == -1) {\n            hashTable[ch] = index;\n        } else if (hashTable[ch] >= 0) {\n            hashTable[ch] = -2;\n        }\n\n        index++;\n    }\n    //return the first appearance once char in current string stream\n    public char FirstAppearingOnce()\n    {\n        char c = '#';\n        int minIndex = Integer.MAX_VALUE;\n\n        for (int i = 0; i < TABLE_SIZE; i++) {\n            if (hashTable[i] >= 0 && hashTable[i] < minIndex) {\n                c = (char)i;\n                minIndex = hashTable[i];\n            }\n        }\n\n        return c;\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_50_StringUtilsSolutions.java",
    "content": "package com.ex.offer;\n\nimport org.junit.Test;\n\nimport java.util.HashMap;\n\npublic class Ex_50_StringUtilsSolutions {\n\n    public String deleteString(String str1, String str2) {\n        if (str1 == null || str1.length() <= 0) return null;\n\n        if (str2 == null || str2.length() <= 0) return str1;\n\n        HashMap<Character, Integer> map = new HashMap<>();\n        for (int i = 0;  i < str2.length(); i++) {\n            map.put(str2.charAt(i), 1);\n        }\n\n        StringBuilder sb = new StringBuilder();\n        for (int i = 0; i < str1.length(); i++) {\n            if (!map.containsKey(str1.charAt(i))) {\n                sb.append(str1.charAt(i));\n            }\n        }\n\n        return sb.toString();\n    }\n\n    public String deleteDuplicatedChar(String str) {\n        if (str == null || str.length() <= 0) {\n            return null;\n        }\n\n        HashMap<Character, Integer> map = new HashMap<>();\n        for (int i = 0; i < str.length(); i++) {\n            if (!map.containsKey(str.charAt(i))) {\n                map.put(str.charAt(i), 1);\n            } else {\n                map.put(str.charAt(i), map.get(str.charAt(i)).intValue() + 1);\n            }\n        }\n\n        StringBuilder sb = new StringBuilder();\n        for (int i = 0; i < str.length(); i++) {\n            if (map.get(str.charAt(i)).intValue() > 1) {\n                sb.append(str.charAt(i));\n                map.put(str.charAt(i), 0);\n            }\n\n            if (map.get(str.charAt(i)).intValue() == 1) {\n                sb.append(str.charAt(i));\n            }\n        }\n\n        return sb.toString();\n    }\n\n    public boolean isAnagram(String str1, String str2) {\n        if (str1 == null || str1.length() <= 0 || str2 == null || str2.length() <= 0 || str1.length() != str2.length()) {\n            return false;\n        }\n\n        HashMap<Character, Integer> map = new HashMap<>();\n        for (int i = 0; i < str1.length(); i++) {\n            if (!map.containsKey(str1.charAt(i))) {\n                map.put(str1.charAt(i), 1);\n            } else {\n                map.put(str1.charAt(i), map.get(str1.charAt(i)).intValue() + 1);\n            }\n        }\n\n        for (int i = 0; i < str2.length(); i++) {\n            if (map.containsKey(str2.charAt(i))) {\n                map.put(str2.charAt(i), map.get(str2.charAt(i)).intValue()-1);\n            }\n        }\n\n        for (Character c : map.keySet()) {\n            if (map.get(c).intValue() != 0) {\n                return false;\n            }\n        }\n        return true;\n    }\n\n    @Test\n    public void testDeleteString() {\n        String str1 = \"We are students\";\n        String str2 = \"aeiou\";\n        System.out.println(deleteString(str1, str2));\n    }\n\n    @Test\n    public void testDeleteDuplicatedChar() {\n        String str = \"google\";\n        System.out.println(deleteDuplicatedChar(str));\n    }\n\n    @Test\n    public void testIsAnagram() {\n        String str1 = \"silent\";\n        String str2 = \"listen\";\n        String str3 = \"livexy\";\n        System.out.println(isAnagram(str1, str2));\n        System.out.println(isAnagram(str1, str3));\n    }\n\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_51_InversePairs.java",
    "content": "package com.ex.offer;\n\nimport java.util.Arrays;\n\npublic class Ex_51_InversePairs {\n    public int InversePairs(int [] array) {\n        if (array == null || array.length < 2) {\n            return 0;\n        }\n        int[] copy = Arrays.copyOf(array, array.length);\n        int count = mergeSort(array, 0, array.length-1);\n\n        return count;\n    }\n\n    private int mergeSort(int[] array, int low, int high) {\n        if (low == high) {\n            return 0;\n        }\n\n        int mid = low + ((high-low) >> 1);\n        int left = mergeSort(array, low, mid);\n        int right = mergeSort(array, mid+1, high);\n        int merge = merge(array, low, mid, high);\n        return left + right + merge ;\n    }\n\n    private int merge(int[] array, int low, int mid, int high) {\n        int[] help = new int[high-low+1];\n        int i = 0;\n        int p1 = low;\n        int p2 = mid+1;\n        int res = 0;\n\n        while (p1 <= mid && p2 <= high) {\n            res += array[p1] > array[p2] ? (high-p2+1) : 0;\n            help[i++] = array[p1] > array[p2] ? array[p1++] : array[p2++];\n        }\n\n        while (p1 <= mid) {\n            help[i++] = array[p1++];\n        }\n\n        while (p2 <= high) {\n            help[i++] = array[p2++];\n        }\n\n        for (i = 0; i < help.length; i++) {\n            array[low + i] = help[i];\n        }\n\n        return res;\n    }\n\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_51_InversePairs_BigData.java",
    "content": "package com.ex.offer;\n\nimport java.util.Arrays;\n\npublic class Ex_51_InversePairs_BigData {\n    public int InversePairs(int [] array) {\n        if (array == null || array.length < 2) {\n            return 0;\n        }\n\n        int count = mergeSort(array, 0, array.length-1);\n\n        return count;\n    }\n\n    private int mergeSort(int[] array, int low, int high) {\n        if (low == high) {\n            return 0;\n        }\n\n        int mid = low + ((high-low) >> 1);\n        int left = mergeSort(array, low, mid);\n        int right = mergeSort(array, mid+1, high);\n        int merge = merge(array, low, mid, high);\n\n        return (left + right + merge) % 1000000007 ;\n    }\n\n    private int merge(int[] array, int low, int mid, int high) {\n        int[] help = new int[high-low+1];\n        int i = 0;\n        int p1 = low;\n        int p2 = mid+1;\n        int res = 0;\n\n        while (p1 <= mid && p2 <= high) {\n            res += array[p1] > array[p2] ? (high-p2+1): 0;\n            res = res >= 1000000007? res % 1000000007 : res;   // 数据过大，会溢出\n            help[i++] = array[p1] > array[p2] ? array[p1++] : array[p2++];\n        }\n\n        while (p1 <= mid) {\n            help[i++] = array[p1++];\n        }\n\n        while (p2 <= high) {\n            help[i++] = array[p2++];\n        }\n\n        for (i = 0; i < help.length; i++) {\n            array[low + i] = help[i];\n        }\n\n        return res;\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_52_FirstCommonNode.java",
    "content": "package com.ex.offer;\n\npublic class Ex_52_FirstCommonNode {\n    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {\n        if (pHead1 == null || pHead2 == null) {\n            return null;\n        }\n\n        int len1 = getLengthOfList(pHead1);\n        int len2 = getLengthOfList(pHead2);\n        int diff = Math.abs(len1-len2);\n\n        ListNode longListHead = len1 > len2 ? pHead1 : pHead2;\n        ListNode shortListHead = len1 < len2 ? pHead1 : pHead2;\n\n        for (int i = 0; i < diff; i++) {\n            longListHead = longListHead.next;\n        }\n\n        while (longListHead != null && longListHead.val != shortListHead.val) {\n            longListHead = longListHead.next;\n            shortListHead = shortListHead.next;\n        }\n\n        return longListHead != null ? longListHead : null;\n    }\n\n    private int getLengthOfList(ListNode pHead1) {\n        if (pHead1 == null) {\n            return 0;\n        }\n\n        int len = 0;\n        for (ListNode node = pHead1; node != null; node = node.next) {\n            len++;\n        }\n\n        return len;\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_53_GetMissingNumber.java",
    "content": "package com.ex.offer;\n\npublic class Ex_53_GetMissingNumber {\n    public int getMissingNumber(int[] array) {\n        if (array == null || array.length < 1) {\n            return -1;\n        }\n\n        int low = 0;\n        int high = array.length-1;\n        while (low <= high) {\n            int mid = low + ((high - low) >> 1);\n            if (array[mid] != mid) {\n                if (mid == 0 || array[mid-1] == mid-1) {\n                    return mid;\n                }\n                high = mid-1;\n            } else {\n                low = mid + 1;\n            }\n        }\n\n        if (low == array.length-1) {\n            return array.length;\n        }\n        return -1;\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_53_GetNumberOfK.java",
    "content": "package com.ex.offer;\n\nimport org.junit.Test;\n\npublic class Ex_53_GetNumberOfK {\n    public int GetNumberOfK(int [] array , int k) {\n        if (array == null || array.length <= 0) {\n            return 0;\n        }\n\n        int left = getFirstIndexOfK(array, k, 0, array.length-1);\n        int right = getLastIndexOfK(array, k, 0, array.length-1);\n\n        if (left != -1 && right != -1) {\n            return right - left + 1;\n        }\n\n        return 0;\n    }\n\n    private int getFirstIndexOfK(int[] array, int k, int low, int high) {\n        if (low > high) {\n            return -1;\n        }\n\n        int midIndex = low + ((high-low) >> 1);\n        int midData  = array[midIndex];\n        if (midData == k) {\n            if (midIndex > 0 && array[midIndex-1] != midData || midIndex == 0) {\n                return midIndex;\n            } else {\n                high = midIndex-1;\n            }\n        } else if (midData > k) {\n            high = midIndex - 1;\n        } else {\n            low = midIndex + 1;\n        }\n\n        return getFirstIndexOfK(array, k, low, high);\n    }\n\n    private int getLastIndexOfK(int[] array, int k, int low, int high) {\n        if (low > high) {\n            return -1;\n        }\n\n        int midIndex = low + ((high-low) >> 1);\n        int midData  = array[midIndex];\n        if (midData == k) {\n            if (midIndex < array.length-1 && array[midIndex+1] != k || midIndex == array.length-1) {\n                return midIndex;\n            } else {\n                low =  midIndex + 1;\n            }\n        } else if (midData > k) {\n            high = midIndex - 1;\n        } else {\n            low = midIndex + 1;\n        }\n\n        return getLastIndexOfK(array, k, low, high);\n    }\n\n    @Test\n    public void test() {\n        int[] array = new int[]{1,3,3,3,3,3,4,5};\n        System.out.println(getFirstIndexOfK(array, 2, 0, array.length-1));\n        System.out.println(getLastIndexOfK(array, 2, 0, array.length-1));\n        System.out.println(GetNumberOfK(array, 2));\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_53_GetNumberSameAsIndex.java",
    "content": "package com.ex.offer;\n\nimport org.junit.Test;\n\npublic class Ex_53_GetNumberSameAsIndex {\n\n    public int getNumberSameAsIndex(int[] array) {\n        if (array == null || array.length <= 0) {\n            return -1;\n        }\n\n        int low = 0;\n        int high = array.length-1;\n\n        while (low <= high) {\n            int midIndex = low + ((high - low) >> 1);\n            int midData  = array[midIndex];\n\n            if (midData == midIndex) {\n                return midData;\n            } else if (midData > midIndex) {\n                high = midIndex-1;\n            } else {\n                low = midIndex + 1;\n            }\n        }\n\n        return -1;\n    }\n\n    @Test\n    public void test() {\n        int[] array = new int[] {-3,-1,1,3,5};\n        System.out.println(getNumberSameAsIndex(array));\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_54_KthNodeInBST.java",
    "content": "package com.ex.offer;\n\npublic class Ex_54_KthNodeInBST {\n\n    int count = 0; // 递归全局变量\n\n    TreeNode KthNode(TreeNode pRoot, int k)\n    {\n        if (pRoot != null) {\n            TreeNode node = KthNode(pRoot.left, k);\n            if (node != null) {\n                return node;\n            }\n\n            count++;\n            if (count == k) {\n                return pRoot;\n            }\n\n            node = KthNode(pRoot.right, k);\n            if (node != null) {\n                return node;\n            }\n        }\n\n        return null;\n    }\n\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_55_BalancedBT.java",
    "content": "package com.ex.offer;\n\npublic class Ex_55_BalancedBT {\n\n    // Java没有引用和指针，可以使用全局变量，也可以使用数组引用\n    int depth = 0;\n\n    public boolean IsBalanced_Solution(TreeNode root) {\n        return isBalance(root);\n    }\n\n    private boolean isBalance(TreeNode root) {\n        if (root == null) {\n            depth = 0;  // 深度为0\n            return true;\n        }\n\n        boolean left = isBalance(root.left);\n        int leftDepth = depth;  // 左子树深度\n\n        boolean right = isBalance(root.right);\n        int rightDepth = depth; // 右子树深度\n\n        depth = Math.max(leftDepth + 1, rightDepth + 1); // root深度（后序遍历）\n\n        if (left && right && Math.abs(leftDepth - rightDepth) <= 1) {\n            return true;\n        }\n\n        return false;\n    }\n\n    //pos-order遍历，使用辅助数组depth来保存每一步遍历的深度，同时返回该节点是否是平衡的\n    public boolean IsBalanced_Solution1(TreeNode root) {\n        return isBalance(root, new int[1]);\n    }\n\n    public boolean isBalance(TreeNode root, int[] depth) {\n        if (root == null) {\n            depth[0] = 0;\n            return true;\n        }\n        boolean left = isBalance(root.left, depth);\n        int leftdepth = depth[0];\n\n        boolean right = isBalance(root.right, depth);\n        int rightdepth = depth[0];\n\n        depth[0] = Math.max(leftdepth + 1, rightdepth + 1);\n\n        if (left && right && Math.abs(leftdepth - rightdepth) <= 1) return true;\n        return false;\n    }\n\n    // 从上到下遍历: 遍历每个结点，借助一个获取树深度的递归函数，\n    // 根据该结点的左右子树高度差判断是否平衡，然后递归地对左右子树进行判断。\n    public boolean IsBalanced_Solution2(TreeNode root) {\n        if (root == null) {\n            return true;\n        }\n\n        int leftDepth = TreeDepth(root.left);\n        int rightDepth = TreeDepth(root.right);\n        int diff = leftDepth - rightDepth;\n\n        if (diff > 1 || diff < -1) {\n            return false;\n        }\n\n        return IsBalanced_Solution2(root.left) && IsBalanced_Solution2(root.right);\n    }\n\n    private int TreeDepth(TreeNode root) {\n        if (root == null) {\n            return 0;\n        }\n\n        int leftTreeDepth = TreeDepth(root.left);\n        int rightTreeDepth = TreeDepth(root.right);\n\n        return leftTreeDepth > rightTreeDepth ? (leftTreeDepth + 1) : (rightTreeDepth + 1);\n    }\n\n    // 从下到上遍历:\n    // 从上到下遍历在判断上层结点的时候，会多次重复遍历下层结点，增加了不必要的开销。\n    // 如果改为从下往上遍历，如果子树是平衡二叉树，则返回子树的高度；\n    // 如果发现子树不是平衡二叉树，则直接停止遍历，这样至多只对每个结点访问一次。\n    public boolean IsBalanced_Solution3(TreeNode root) {\n        return getDepth(root) != -1;\n    }\n\n    // 若左右子树高度差大于1，则返回-1（不是平衡二叉树）\n    // 若左右子树高度差不大于1，则返回子树的高度\n    private int getDepth(TreeNode root) {\n        if (root == null) {\n            return 0;\n        }\n\n        int leftDepth = getDepth(root.left);\n        if (leftDepth == -1) return -1;\n\n        int rightDepth = getDepth(root.right);\n        if (rightDepth == -1) return -1;\n\n        return Math.abs(leftDepth - rightDepth) > 1 ? -1 : (Math.max(leftDepth, rightDepth) + 1);\n    }\n\n\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_55_DepthOfBT.java",
    "content": "package com.ex.offer;\n\npublic class Ex_55_DepthOfBT {\n    public int TreeDepth(TreeNode root) {\n        if (root == null) {\n            return 0;\n        }\n\n        int leftTreeDepth = TreeDepth(root.left);\n        int rightTreeDepth = TreeDepth(root.right);\n\n        return leftTreeDepth > rightTreeDepth ? (leftTreeDepth + 1) : (rightTreeDepth + 1);\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_56_AppearanceOnce.java",
    "content": "package com.ex.offer;\n\n//num1,num2分别为长度为1的数组。传出参数\n//将num1[0],num2[0]设置为返回结果\npublic class Ex_56_AppearanceOnce {\n    public void FindNumsAppearOnce(int [] array,int num1[] , int num2[]) {\n        if (array == null || array.length < 2) {\n            return;\n        }\n\n        int xor = 0;\n        for (int i = 0; i < array.length; i++) {\n            xor = xor ^ array[i];   // xor = a ^ b =  num1[0] ^ num2[0]\n        }\n\n        int indexOf1 = findFirst1_Bit(xor);\n\n        for (int i = 0; i < array.length; i++) {\n            if (is1_Bit(array[i], indexOf1)) {\n                num1[0] = num1[0] ^ array[i];\n            } else {\n                num2[0] = num2[0] ^ array[i];\n            }\n        }\n    }\n\n    // 从右到左第1bit为1的index\n    private int findFirst1_Bit(int num) {\n        int index = 0;\n        int len = 8 * 4;\n        while (index < len && (num & 1) == 0) {\n            num = num >> 1;\n            index++;\n        }\n        return index;\n    }\n\n    // 判断从右到左第index位是不是1\n    private boolean is1_Bit(int num, int index) {\n        num = num >> index;\n        return (num & 1) == 1;\n    }\n\n\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_56_AppearanceOnce_Continued.java",
    "content": "package com.ex.offer;\n\nimport org.junit.Test;\n\npublic class Ex_56_AppearanceOnce_Continued {\n    public int FindNumAppearOnce(int[] array) {\n        if (array == null || array.length < 1) {\n            return -1;\n        }\n\n        int[] bitSum = new int[8 * 4];// 所有元素的各个bit分别相加\n\n        for (int i = 0; i < array.length; i++) {\n            int bitFlag = 1;  // bit & 1 = bit 如：xxx & 010 = 0x0\n            for (int j = 31; j >= 0; j--) {\n                int bit = array[i] & bitFlag;  // 每一位都是0x0...或者000...\n                bitSum[j] += bit == 0 ? 0 : 1; // 但是这里只能加1或者0\n                bitFlag = bitFlag << 1;\n            }\n        }\n\n        int result = 0;\n        for (int i = 0; i < 32; i++) {\n            result = result << 1;\n            result += bitSum[i] % 3;\n        }\n\n        return result;\n    }\n\n    @Test\n    public void test() {\n        int[] array = new int[] {4, 5,5,5,9,9,9,8,8,8, 20, 4,4};\n        System.out.println(FindNumAppearOnce(array));\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_57_FindContinuousSequence.java",
    "content": "package com.ex.offer;\n\nimport org.junit.Test;\n\nimport java.util.ArrayList;\n\npublic class Ex_57_FindContinuousSequence {\n    public ArrayList<ArrayList<Integer>> FindContinuousSequence(int sum) {\n        ArrayList<ArrayList<Integer>> res = new ArrayList<>();\n        if (sum < 3) {\n            return res;\n        }\n\n        int small = 1;\n        int big = 2;\n        int mid = (sum + 1) / 2;\n        int curSum = small+big;\n\n        while (small < mid) {\n            if (curSum == sum) {\n                res.add(new ArrayList<>(full(small, big))); // 一定要注意这里，要拷贝构造，不能直接传入引用\n            }\n\n            while (curSum > sum && small < mid) {\n                curSum -= small;\n                small++;\n                if (curSum == sum) {\n                    res.add(new ArrayList<>(full(small, big)));\n                }\n            }\n            big++;\n            curSum+=big;\n        }\n        return res;\n    }\n\n    private ArrayList<Integer> full(int small, int big) {\n        ArrayList<Integer> list = new ArrayList<>();\n        for (int i = small; i <= big; i++) {\n            list.add(i);\n        }\n        return list;\n    }\n\n    @Test\n    public void test() {\n        ArrayList<ArrayList<Integer>> list = FindContinuousSequence(15);\n        for (ArrayList<Integer> x : list) {\n            for (Integer i : x) {\n                System.out.print(i + \" \");\n            }\n            System.out.println();\n        }\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_57_FindNumbersWithSum.java",
    "content": "package com.ex.offer;\n\nimport org.junit.Test;\n\nimport java.util.ArrayList;\n\npublic class Ex_57_FindNumbersWithSum {\n    public ArrayList<Integer> FindNumbersWithSum(int [] array, int sum) {\n        ArrayList<Integer> res = new ArrayList<>();\n        if (array == null || array.length <= 1) return res;\n\n        int left = 0;\n        int right = array.length-1;\n        int curSum = 0;\n        ArrayList<Integer> leftList = new ArrayList<>();\n        ArrayList<Integer> rightList = new ArrayList<>();\n        boolean isFound = false;\n        while (left < right) {\n            curSum = array[left] + array[right];\n            if (curSum == sum) {\n                leftList.add(left);\n                rightList.add(right);\n                left++;\n                right--;\n                isFound = true;\n            } else if (curSum < sum) {\n                left++;\n            } else {\n                right--;\n            }\n        }\n        if (!isFound) return res;\n\n        int min = Integer.MAX_VALUE;\n        int minLeft = -1;\n        int minRight = -1;\n        for (int i = 0; i < leftList.size(); i++) {\n            int tmp = array[leftList.get(i)] * array[rightList.get(i)];\n            if (tmp < min) {\n                min = tmp; // 注意修改min的值\n                minLeft = leftList.get(i);\n                minRight = rightList.get(i);\n            }\n        }\n\n        if (minLeft != -1) {\n            res.add(array[minLeft]);\n            res.add(array[minRight]);\n        }\n\n        return res;\n    }\n\n    @Test\n    public void test() {\n        int[] array = new int[] {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};\n        ArrayList<Integer> res = FindNumbersWithSum(array, -1);\n        for (Integer i : res) {\n            System.out.println(i);\n        }\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_58_ROL.java",
    "content": "package com.ex.offer;\n\nimport org.junit.Test;\n\npublic class Ex_58_ROL {\n    public String LeftRotateString(String str,int n) {\n        if (str == null || str.length() <= 0 || n < 0 || n > str.length()) {\n            return \"\";\n        }\n\n        char[] chars = str.toCharArray();\n\n        reverse(chars, 0, n-1);\n        reverse(chars, n, chars.length-1);\n        reverse(chars, 0, chars.length-1);\n\n        return String.valueOf(chars);\n    }\n\n    private void reverse(char[] chars, int start, int end) {\n        for (int i = start, j = end; i <= j; i++, j--) {\n            char temp = chars[i];\n            chars[i] = chars[j];\n            chars[j] = temp;\n        }\n    }\n\n    @Test\n    public void test() {\n        String str = \"abcXYZdef\";\n        System.out.println(LeftRotateString(str, 3));\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_58_ReverseSentence.java",
    "content": "package com.ex.offer;\n\nimport org.junit.Test;\n\npublic class Ex_58_ReverseSentence {\n    public String ReverseSentence(String str) {\n        // 边界条件1：str == null or str = \"\"\n        if (str == null || str.length() <= 0) {\n            return \"\";\n        }\n\n        // 注意这里：String是不可变的，因此我们需要将String转换为char[]\n        char[] chars = str.toCharArray();\n        reverse(chars, 0, chars.length-1);\n\n        int start = 0; // 指向单词的开头\n        while (start < chars.length && chars[start] == ' ') {\n            start++;  // 排除开头的' '\n        }\n\n        // 边界条件2：str = \"                   \" (全部都是' ')\n        if (start == chars.length) {\n            return str;\n        }\n\n        // start 和 end像是在接力\n        for (int end = start; end < chars.length; end++) {\n            if (chars[end] == ' ') {\n                reverse(chars, start, --end);\n                end += 2;\n                start = end;\n            }\n        }\n\n        reverse(chars, start, chars.length-1);\n\n        return String.valueOf(chars);\n    }\n\n    private void reverse(char[] chars, int start, int end) {\n        for (int i = start, j = end; i <= j; i++, j--) {\n            char temp = chars[i];\n            chars[i] = chars[j];\n            chars[j] = temp;\n        }\n    }\n\n\n    @Test\n    public void test() {\n        String str = \"I am a student.\";\n        String str1 = \" \";\n        System.out.println(ReverseSentence(str));\n        //System.out.println(ReverseSentence(str1));\n        System.out.println(str1.length());\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_59_MaxNumOfSlidingWindow.java",
    "content": "package com.ex.offer;\n\nimport org.junit.Test;\n\nimport java.util.ArrayList;\nimport java.util.LinkedList;\n\npublic class Ex_59_MaxNumOfSlidingWindow {\n    public ArrayList<Integer> maxInWindows(int [] num, int size)\n    {\n        ArrayList<Integer> res = new ArrayList<>();\n\n        if (num == null || num.length <= 0 || size <= 0 || size > num.length) {\n            return res;\n        }\n\n        LinkedList<Integer> qMax = new LinkedList<>();  // 双端队列：左端更新max,右端添加数据\n\n        int left = 0;\n\n        for (int right = 0; right < num.length; right++) {\n            // 更新右端数据\n            while (!qMax.isEmpty() && num[qMax.peekLast()] <= num[right]) {\n                qMax.pollLast();\n            }\n\n            qMax.addLast(right);\n\n            // 更新max：如果max的索引不在窗口内,则更新\n            if (qMax.peekFirst() == right - size) {\n                qMax.pollFirst();\n            }\n\n            // 待窗口达到size，输出max\n            if (right >= size-1) {\n                res.add(num[qMax.peekFirst()]);\n                left++;\n            }\n        }\n\n        return res;\n    }\n\n    @Test\n    public void test() {\n        int[] num = new int[] {2,3,4,2,6,2,5,1};\n        int size = 3;\n        ArrayList<Integer> list = maxInWindows(num, size);\n        for (Integer i : list) {\n            System.out.print(i + \" \");\n        }\n    }\n\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_59_QueueWithMax.java",
    "content": "package com.ex.offer;\n\nimport org.junit.Test;\n\nimport java.util.LinkedList;\n\npublic class Ex_59_QueueWithMax {\n    private LinkedList<Integer> data = new LinkedList<>();\n    private LinkedList<Integer> qMax = new LinkedList<>();\n\n    public void push_back(Integer x) {\n\n        if (!qMax.isEmpty() && qMax.peekLast() > x) {\n            qMax.addLast(qMax.peek());\n        }\n\n        qMax.addLast(x);\n        data.addLast(x);\n    }\n\n    public Integer pop_front() {\n        if (!data.isEmpty()) {\n            qMax.pollFirst();\n            return data.pollFirst();\n        }\n\n        return null;\n    }\n\n    public Integer max() {\n        if (!qMax.isEmpty()) {\n            return qMax.peekFirst();\n        }\n        return null;\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_60_ProbabilityOfS.java",
    "content": "package com.ex.offer;\n\nimport org.junit.Test;\n\n// https://www.cnblogs.com/keedor/p/4474471.html\n// https://www.cnblogs.com/AndyJee/p/4686208.html\npublic class Ex_60_ProbabilityOfS {\n    private static final int MAX_VALUE = 6; // 骰子的最大点数\n\n    // probability(n, currentLeft, currentSum, sum)\n    public void printProbability_1(int number) {\n        if (number < 1) {\n            return;\n        }\n\n        int maxSum = number * MAX_VALUE;\n        int[] sums = new int[maxSum-number + 1];\n\n        for (int i = 0; i < sums.length; i++) {\n            sums[i] = 0;\n        }\n\n        probability(number, sums);\n\n        double total = Math.pow(MAX_VALUE, number);\n        for (int i = 0; i < sums.length; i++) {\n            System.out.println(sums[i]/total);\n        }\n    }\n\n    private void probability(int number, int[] sums) {\n        for(int i = 1; i <= MAX_VALUE; i++) {\n            probability(number, number - 1, i, sums);\n        }\n    }\n\n    /**\n     * @param number : 总共几个骰子\n     * @param current：现在剩下几个骰子\n     * @param sum：现在已有的和\n     * @param sums\n     */\n    private void probability(int number, int current, int sum, int[] sums) {\n        if (current == 0) {\n            sums[sum - number]++;\n            return;\n        }\n        for (int i = 1; i <= MAX_VALUE; i++) {\n            probability(number, current-1, sum + i, sums);\n        }\n    }\n\n    /**\n     *\n     * k:骰子个数\n     * n:点数和\n     * f(k, n) = f(k-1, n-1) + f(k-1, n-2) + f(k-1, n-3) + f(k-1, n-4) + f(k-1, n-5) + f(k-1, n-6);\n     * f(k-1, n-1):表示第k-1个骰子投了n-1点，则第k个骰子投1个点就可以得到n\n     * f(n) = f(n-1) + f(n-2) + f(n-3) + f(n-4) + f(n-5) + f(n-6)\n     * @param number\n     */\n    public void printProbability_2(int number) {\n        if (number < 1) {\n            return;\n        }\n\n        /**\n         * 我们需要将中间值存起来以减少递归过程中的重复计算问题，可以考虑我们用两个数组AB，\n         * A在B之上得到，B又在A之上再次得到，这样AB互相作为对方的中间值，\n         * 其实这个思想跟斐波拉契迭代算法中用中间变量保存n-1，n-2的值有异曲同工之妙\n         */\n        int[][] sums = new int[2][MAX_VALUE * number + 1]; // [1,number]\n\n        int flag = 0;\n        // 抛掷第一枚骰子 [1,2,3,...,MAX_VALUE]\n        for (int i = 1; i <= MAX_VALUE; i++) {\n            sums[flag][i] = 1;\n        }\n\n        // 第二次抛掷骰子开始\n        for (int k = 2; k <= number; k++) {\n            // 第k次掷色子,和最小为k,和最大为MAX_VALUE * k\n            for (int i = k; i <= MAX_VALUE * k; i++) {\n                int temp = 0;\n                for (int j = 1; j <= i && j <= MAX_VALUE; j++) { // j<=i,防止数组越界\n                    temp += sums[flag][i-j];\n                }\n                sums[1-flag][i] = temp;\n            }\n            flag = 1- flag;\n        }\n\n        double total = Math.pow(MAX_VALUE, number);\n        for (int i = number; i < sums[flag].length; i++) {\n            System.out.println(sums[flag][i]/total);\n        }\n    }\n\n    @Test\n    public void test1() {\n        printProbability_1(2);\n        System.out.println();\n    }\n\n    @Test\n    public void test2() {\n        printProbability_2(2);\n    }\n\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_61_ContinuousSequence.java",
    "content": "package com.ex.offer;\n\nimport java.util.Arrays;\n\npublic class Ex_61_ContinuousSequence {\n    public boolean isContinuous(int [] numbers) {\n        if (numbers == null || numbers.length < 5) {\n            return false;\n        }\n\n        Arrays.sort(numbers);\n\n        int numberOfZero = 0;\n        int gap = 0;\n\n        for (int i = 0; i < numbers.length && numbers[i] == 0; i++) {\n            numberOfZero++;\n        }\n\n        int small = numberOfZero; // 0之后的第一位索引\n        int big = small + 1;\n\n        while (big < numbers.length) {\n            if (numbers[small] == numbers[big]) {\n                return false;\n            }\n\n            gap += numbers[big] - numbers[small] - 1;\n            small = big;\n            big++;\n        }\n\n        return gap > numberOfZero ? false : true;\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_62_Josephus.java",
    "content": "package com.ex.offer;\n\nimport org.junit.Test;\n\nimport java.util.ArrayList;\n\n// 约瑟夫问题其实是一个环型链表\n// 假设 n > m, 则第一个要删除的位置是 index = m-1, 第二个是 (index + m) % size\n// 每次要删除的位置是 (lastIndex + m) % size;\npublic class Ex_62_Josephus {\n    public int LastRemaining_Solution(int n, int m) {\n        if (n <= 0 || m <= 0) {\n            return -1;\n        }\n\n        ArrayList<Integer> list = new ArrayList<>();\n\n        for (int i = 0; i < n; i++) {\n            list.add(i);\n        }\n\n        int index = -1;\n\n        while (list.size() > 1) {\n            index = (index + m) % list.size();\n            list.remove(index);\n            index--;\n        }\n\n        return list.get(0);\n    }\n\n    /**\n     * f(n, m) = [f(n-1, m) + m] % n (n > 1)\n     *\n     * @param n\n     * @param m\n     * @return\n     */\n    public int LastRemaining_Solution1(int n, int m) {\n        if (n <= 0 || m <= 0) {\n            return -1;\n        }\n\n        int lastRemain = 0;\n        for (int i = 2; i <= n; i++) {\n            lastRemain = (lastRemain + m) % i;\n        }\n        return lastRemain;\n    }\n    @Test\n    public void test() {\n        System.out.println(LastRemaining_Solution(5, 3));\n        System.out.println(LastRemaining_Solution1(5, 3));\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_63_MaxProfits.java",
    "content": "package com.ex.offer;\n\nimport org.junit.Test;\n\n// 此题目类似于Ex_42_MaxSumOfSubArray\npublic class Ex_63_MaxProfits {\n    public int maxProfits(int[] prices) {\n        if (prices == null || prices.length < 2) {\n            return -1;\n        }\n\n        int minPrice = prices[0]; // i之前[0,i-1]的最小值，控制左侧\n        int maxDiff = prices[1] - minPrice; // 控制右侧，遍历了所有可能最大差值\n\n        for (int i = 2; i < prices.length; i++) {\n            int curDiff = prices[i] - minPrice;\n\n            if (curDiff > maxDiff) {\n                maxDiff = curDiff;\n            }\n\n            if (prices[i] < minPrice) {\n                minPrice = prices[i];\n            }\n        }\n\n        return maxDiff;\n    }\n\n    @Test\n    public void test() {\n        int[] prices = new int[] {9,11,8,5,7,12,16,14};\n        System.out.println(maxProfits(prices));\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_64_SumFrom1ToN.java",
    "content": "package com.ex.offer;\n\nimport org.junit.Test;\n\npublic class Ex_64_SumFrom1ToN {\n    public int Sum_Solution(int n) {\n        int sum = n;\n        boolean stop = (n > 0) && ((sum += Sum_Solution(n-1)) > 1);\n        return sum;\n    }\n\n    @Test\n    public void test() {\n        System.out.println(Sum_Solution(10));\n    }\n\n}\n\n\n\n\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_65_AddWithoutCarry.java",
    "content": "package com.ex.offer;\n\npublic class Ex_65_AddWithoutCarry {\n    public int Add(int num1,int num2) {\n        int sum = 0;\n        int carry = 0;\n        do {\n            sum = num1 ^ num2; //不进位加法（不断执行不进位加法，直到进位为0，则不进位加法=进位加法）\n            carry = (num1 & num2) << 1;\n\n            num1 = sum;\n            num2 = carry;\n        } while (num2 != 0);\n\n        return sum;\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_65_SwapNumWithoutTemp.java",
    "content": "package com.ex.offer;\n\npublic class Ex_65_SwapNumWithoutTemp {\n    public int[] swap1 (int a, int b) {\n        int[] res = new int[2];\n        //=================================\n        a = a + b;\n        b = a - b;  // b = (a + b) - b\n        a = a - b;  // a = (a + b) - a\n        //=================================\n        res[0] = a;\n        res[1] = b;\n        return res;\n    }\n\n    public int[] swap2 (int a, int b) {\n        int[] res = new int[2];\n\n        //=================================\n        a = a ^ b;\n        b = a ^ b;   // b = (a ^ b) ^ b = a ^ (b ^ b) = a ^ 0 = a\n        a = a ^ b;\n        //=================================\n        res[0] = a;\n        res[1] = b;\n        return res;\n    }\n\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_66_ConstructMultiplyArray.java",
    "content": "package com.ex.offer;\n\npublic class Ex_66_ConstructMultiplyArray {\n    public int[] multiply(int[] A) {\n        int[] res = new int[A.length];\n        if (A == null || A.length < 2) {\n            return res;\n        }\n\n        int[] C = new int[A.length];\n        int[] D = new int[A.length];\n        C[0] = 1;\n        D[D.length-1] = 1;\n\n        for (int i = 1; i < C.length; i++) {\n            C[i] = C[i-1] * A[i-1];\n        }\n\n        for (int i = D.length-2; i >= 0; i--) {\n            D[i] = D[i+1] * A[i+1];\n        }\n\n        for (int i = 0; i < res.length; i++) {\n            res[i] = C[i] * D[i];\n        }\n\n        return res;\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_67_StringToInt.java",
    "content": "package com.ex.offer;\n\nimport org.junit.Test;\n\npublic class Ex_67_StringToInt {\n    /**\n     * 说明：当输入不合法时，返回0。但是由于正常输出也可能有0，\n     * 因此需要设置全局变量isValid标记返回的0是因为输入不合法返回\n     *\n     * @param str\n     * @return\n     */\n    public int StrToInt(String str) {\n        boolean isValid = true;\n        // 边界1：str = null\n        // 边界2：str = \"\"\n        if (str == null || str == \"\") {\n            isValid = false;\n            return 0;\n        }\n\n        int number = 0;\n        boolean minus = false;\n\n        for (int i = 0; i < str.length(); i++) {\n            char c = str.charAt(i);\n\n            if (i == 0) {\n                if (c == '+') continue;\n                if (c == '-') {\n                    minus = true;\n                    continue;\n                }\n            }\n\n            // 边界3：输入存在非法字符\n            // [0,1,2,...,9]的ASII码[48,49,...,57]\n            // a = 97\n            // A = 65\n            // x = (char)x - '0' (char -> int)\n            if (c < 48 || c > 57) {\n                isValid = false;\n                return 0;\n            }\n            number = number * 10 + (c - '0');\n        }\n\n        return minus ? -1 * number : number;\n    }\n\n    @Test\n    public void test() {\n        String str1 = null;\n        String str2 = \"\";  // str2 = \"         \";\n        String str3 = \"1234\";\n        String str4 = \"+1234\";\n        String str5 = \"-1234\";\n        String str6 = \"123a5\";\n\n        System.out.println(StrToInt(str1));\n        System.out.println(StrToInt(str2));\n        System.out.println(StrToInt(str3));\n        System.out.println(StrToInt(str4));\n        System.out.println(StrToInt(str5));\n        System.out.println(StrToInt(str6));\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Ex_68_LowestCommonAncestor.java",
    "content": "package com.ex.offer;\n\npublic class Ex_68_LowestCommonAncestor {\n    // case1: 二叉树（二叉搜索树）\n    public TreeNode commonAncestor(TreeNode root, TreeNode node1, TreeNode node2) {\n        if (root == null) {\n            return null;\n        }\n\n        return null;\n    }\n\n    // case2: 不是二叉树，但是存在指向父节点的指针\n\n    // case3: 不是二叉树，不存在指向父节点的指针\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/ListNode.java",
    "content": "package com.ex.offer;\n\n/**\n * 单链表节点\n */\n\npublic class ListNode {\n    int val;\n    ListNode next;\n\n    public ListNode(int val) {\n        this.val = val;\n    }\n\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/Node.java",
    "content": "package com.ex.offer;\n\n/**\n * 单链表节点\n */\npublic class Node {\n    int val;\n    Node next;\n\n    Node (int val) {\n        this.val = val;\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/RandomListNode.java",
    "content": "package com.ex.offer;\n\n/**\n * 含有指向随机节点指针的单链表节点\n */\npublic class RandomListNode {\n    int label;\n    RandomListNode next = null;\n    RandomListNode random = null;\n\n    RandomListNode(int label) {\n        this.label = label;\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/TestUtils.java",
    "content": "package com.ex.offer;\n\nimport java.util.Arrays;\n\npublic class TestUtils {\n    public static void printArray(int[] arr) {\n        for (int i : arr) {\n            System.out.print(i + \" \");\n        }\n        System.out.println();\n    }\n\n    public static void sort(int[] arr) {\n        Arrays.sort(arr);\n    }\n\n    public static int partition(int[] arr, int low, int high) {\n        if (low == high) {\n            return low;\n        }\n\n        int pIndex = low + (int) (Math.random() *(high - low));\n        swap(arr, low, pIndex);\n\n        int pivot = arr[low];\n\n        int i = low;\n        int j = high + 1;\n\n        while (i < j) {\n            while (arr[++i] < pivot) {\n                if (i == high) {\n                    break;\n                }\n            }\n\n            while (arr[--j] > pivot) {\n                if (j == low) {\n                    break;\n                }\n            }\n\n            if (i > j) {\n                break;\n            }\n\n            swap(arr, i, j);\n        }\n        swap(arr, j, low);\n\n        return j;\n    }\n\n    public static void swap(int[] arr, int i, int j) {\n        int tmp = arr[i];\n        arr[i] = arr[j];\n        arr[j] = tmp;\n    }\n\n    // cal\n    public static int getDigitSum(int x) {\n        int sum = 0;\n        while (x > 0) {\n            sum += x % 10;\n            x =  x / 10;\n        }\n\n        return sum;\n    }\n\n    /**\n     * 判断x的奇偶性\n     * if x is odd, then x & 1 == 1   3 & 1 = 0011 & 0001 = 0001\n     * if x is even, then x & 1 == 0  2 & 1 = 0010 & 0001 = 0000\n     *\n     * @param x\n     * @return\n     */\n    public static boolean isOdd(int x) {\n        if ((x & 0x1) == 1) {\n            return true;\n        }\n\n        return false;\n    }\n\n    public static void printStingToInt(StringBuffer s) {\n        System.out.println(s.toString());\n        for (int i = 0; i < s.length(); i++) {\n            int num1 = s.charAt(i);           // 返回s中各个字符的ASII码\n            int num2 = s.charAt(i) - '0';     // 返回s中各个字符的ASII码 - ‘0’的ASII码\n            System.out.print(\"s.charAt(i) = \" + s.charAt(i) + \"; int(s.charAt(i)) = \"\n                    + num1 + \"; int(s.charAt(i) - '0') = \" + num2);\n            System.out.println();\n        }\n    }\n\n    /**\n     * 大数问题：字符串模拟加法\n     *\n     * @param s\n     * @return\n     */\n    public static boolean Increment(StringBuffer s) {\n        boolean isOverflow = false;\n        int nTakeOver = 0; // 进位\n        int nLength = s.length();\n\n        for (int i = nLength - 1; i >= 0; i--) {\n            int nSum = s.charAt(i) - '0' + nTakeOver;\n            // 加1操作：如果是最后一位，增加1\n            if (i == nLength - 1) {\n                nSum++;\n            }\n\n            if (nSum >= 10) {\n                if (i == 0) {\n                    isOverflow = true;\n                } else {\n                    nSum -= 10;\n                    nTakeOver = 1;\n                    s.setCharAt(i, (char)('0' + nSum));\n                }\n            } else {  // 若有一位的nSum < 10，则该可以直接退出，不满足 999...99\n                s.setCharAt(i, (char)('0' + nSum));\n                break;\n            }\n        }\n\n        return isOverflow;\n    }\n\n    public static void printList(Node head) {\n        System.out.print(\"Single Linked List: \");\n        if (head == null) {\n            System.out.print(\"empty list.\");\n        }\n\n        for (Node node = head; node != null; node = node.next) {\n            System.out.print(node.val + \" \");\n        }\n\n        System.out.println();\n    }\n\n    public static void printList_ListNode(ListNode head) {\n        System.out.print(\"Single Linked List: \");\n        if (head == null) {\n            System.out.print(\"empty list.\");\n        }\n\n        for (ListNode node = head; node != null; node = node.next) {\n            System.out.print(node.val + \" \");\n        }\n\n        System.out.println();\n    }\n\n    public static void main(String[] args) {\n//        for (int i = 0; i < 10; i++) {\n//            System.out.println(i + \":\" + isOdd(i));\n//        }\n\n        StringBuffer s = new StringBuffer();\n        s.append('9');\n        s.append('9');\n        s.append('9');\n        s.append('9');\n        s.append('9'); //98765\n        //printStingToInt(s);\n\n        Increment(s);\n        System.out.println(s.toString());\n\n    }\n\n\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/TreeLinkNode.java",
    "content": "package com.ex.offer;\n\n/**\n * 含有指向父节点指针的二叉树节点\n * Ex_08_GetNextNodeInBT\n */\npublic class TreeLinkNode {\n    int val;\n    TreeLinkNode left = null;\n    TreeLinkNode right = null;\n    TreeLinkNode parent = null;\n\n    TreeLinkNode(int val) {\n        this.val = val;\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/offer/TreeNode.java",
    "content": "package com.ex.offer;\n\n/**\n * 二叉树节点\n */\npublic class TreeNode {\n    int val;\n    TreeNode left;\n    TreeNode right;\n\n    TreeNode(int x) {\n        this.val = x;\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/singleton/Singleton1.java",
    "content": "package com.ex.singleton;\n\n// V1.0: 饿汉式\npublic class Singleton1 {\n    // instance必须是static变量（类变量）\n    private static Singleton1 instance = new Singleton1();\n\n    // private无参构造函数: Java会自动为没有明确声明构造函数的类，\n    // 定义一个public的无参构造函数，若没有这个private无参构造函数，\n    // 外部可以随意new Singleton\n    private Singleton1() {}\n\n    // getInstance必须是static方法（类方法）\n    public static Singleton1 getInstance() {\n        return instance;\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/singleton/Singleton2.java",
    "content": "package com.ex.singleton;\n\n// V2.0: 懒汉式\npublic class Singleton2 {\n    private static Singleton2 instance = null;\n\n    private Singleton2() {}\n\n    public static Singleton2 getInstance() {\n        if (instance == null) {\n            instance = new Singleton2();\n        }\n\n        return instance;\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/singleton/Singleton3.java",
    "content": "package com.ex.singleton;\n\n// V3.0: 双重校验\npublic class Singleton3 {\n    // volatile提供可见性（工作内存的值能立即在主内存中可见），\n    // 保证getInstance返回的是初始化完全的对象\n    private static volatile Singleton3 instance = null;\n\n    private Singleton3() {}\n\n    public static Singleton3 getInstance() {\n        // 同步之前进行null检查，避免进入代价相对昂贵的同步块\n        if (instance == null) {\n            synchronized (Singleton3.class) {\n                // 持有锁之后进行null检查，避免上一个线程已经初始化变量\n                if (instance == null) {\n                    instance = new Singleton3();\n                }\n            }\n        }\n        return instance;\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/singleton/Singleton4.java",
    "content": "package com.ex.singleton;\n\n// V4.0: 静态内部类\npublic class Singleton4 {\n    private static class SingletonHolder {\n        public static Singleton4 instance = new Singleton4();\n    }\n\n    public static Singleton4 getInstance() {\n        return SingletonHolder.instance;\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/singleton/Singleton5.java",
    "content": "package com.ex.singleton;\n\n// V5.0: 枚举方法\npublic enum Singleton5 {\n    INSTANCE;\n\n    private int id;\n\n    public int getId() {\n        return id;\n    }\n\n    public void setId(int id) {\n        this.id = id;\n    }\n\n    public static void main(String[] args) {\n        //调用\n        Singleton5.INSTANCE.setId(1);\n        Singleton5.INSTANCE.getId();\n    }\n}\n"
  },
  {
    "path": "offer/src/com/ex/singleton/singleton.md",
    "content": "# 单例模式\n\n## 单例模式的好处\n单例模式适用于应用中频繁创建的对象，尤其是频繁创建的重量级对象。\n例如统一的配置文件。\n使用单例模式能够提升性能，减小内存开销。\n\n## 单例模式的实现\n### 1.饿汉式\n饿汉式加载类的时候，就会创建类的实例对象，那么如果不用这个单例的话，就会消耗内存，浪费性能。\n因此，需要懒加载（lazy-load）\n\n### 2.懒汉式\n懒汉式改进了饿汉式的性能问题，但是又带来了一个问题，即线程安全问题。\n在多线程的情况下，会出现多个实例，违背了单例模式的原则。\n\n### 3.双重校验（双检锁）\n双重校验能够保证单例模式的实例唯一性，同时能够兼顾效率和线程安全。\n\n### 4.静态内部类\n静态内部类的方式实现，可以保证多线程对象的唯一性，同时可以降低双重校验中同步锁机制的代价。\n这种方式还有个好处，就是静态内部类不会在单例类加载的时候就加载，而是在调用`getInstance()`\n方法时才加载。\n\n### 5.枚举方法 by Josh Bloch (《Effective Java》作者)\n好处：\n（1）自由序列化\n（2）保证只有一个实例\n（3）线程安全\n"
  },
  {
    "path": "practice/Final.md",
    "content": "# 总结\n\n时间过得很快，不知不觉间，一切就结束了。\n\n无论课程多么精彩，似乎精彩总是他们的，我什么都没有。无论如何，感谢各位工作人员的辛勤付出。\n\n很多课程都没来得及消化和理解，后续仍然需要进一步的学习、总结、实践。\n\n复习总结列表：\n\n1. [《第一课 数组、链表、栈、队列 * 》](https://shimo.im/docs/RCdRgwWjVWJppyJj/ )\n2. [《第二课 前缀和、差分、双指针、单调栈、单调队列》](https://shimo.im/docs/HvwKPhKHk9dcH9Q6/ )\n3. To be continued ...\n\n"
  },
  {
    "path": "practice/README.md",
    "content": "# Practice\n\n"
  },
  {
    "path": "practice/src/io/gkd/ListNode.java",
    "content": "package io.gkd;\n\npublic class ListNode {\n    public int val;\n    public ListNode next;\n\n    public ListNode() {\n    }\n\n    public ListNode(int val) {\n        this.val = val;\n    }\n\n    public ListNode(int val, ListNode next) {\n        this.val = val;\n        this.next = next;\n    }\n}\n\n"
  },
  {
    "path": "practice/src/io/gkd/Node.java",
    "content": "package io.gkd;\n\nimport java.util.List;\n\npublic class Node {\n    public int val;\n    public List<Node> children;\n\n    public Node() {}\n\n    public Node(int _val) {\n        val = _val;\n    }\n\n    public Node(int _val, List<Node> _children) {\n        val = _val;\n        children = _children;\n    }\n}\n"
  },
  {
    "path": "practice/src/io/gkd/TreeNode.java",
    "content": "package io.gkd;\n\npublic class TreeNode {\n    public int val;\n    public TreeNode left;\n    public TreeNode right;\n\n    public TreeNode() {}\n\n    public TreeNode(int val) {\n        this.val = val;\n    }\n\n    public TreeNode(int val, TreeNode left, TreeNode right) {\n        this.val = val;\n        this.left = left;\n        this.right = right;\n    }\n}\n"
  },
  {
    "path": "practice/src/io/gkd/lectures/lecture04/Lc077_Combine.java",
    "content": "package io.gkd.lectures.lecture04;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class Lc077_Combine {\n\n    public List<List<Integer>> combine(int n, int k) {\n        this.n = n;\n        this.k = k;\n        findSubsets(1);\n        return ans;\n    }\n\n    private void findSubsets(int index) {\n        // 剪枝：选的数大于 k 个，或者剩下的全部选了也不够 k 个，就可以直接退出了\n        if (subset.size() > k || subset.size() + n - index + 1 < k) return;\n        if (index == n + 1) {\n            ans.add(new ArrayList<>(subset)); // make a copy\n            return;\n        }\n        findSubsets(index + 1);\n        subset.add(index);\n        findSubsets(index + 1);\n        subset.remove(subset.size() - 1);\n    }\n\n    private List<List<Integer>> ans = new ArrayList<>();\n    private List<Integer> subset = new ArrayList<>();\n    private int n;\n    private int k;\n\n}\n"
  },
  {
    "path": "practice/src/io/gkd/lectures/lecture04/Lc078_SubSets.java",
    "content": "package io.gkd.lectures.lecture04;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\n/**\n * Medium\n * 78. https://leetcode-cn.com/problems/subsets/submissions/\n */\npublic class Lc078_SubSets {\n\n    public List<List<Integer>> subsets(int[] nums) {\n        findSubsets(nums, 0);\n        return ans;\n    }\n\n    // 递归去枚举 nums[0], nums[1], nums[2], ..., nums[n-1] 这 n 个数选或者不选\n    private void findSubsets(int[] nums, int index) {\n        if (index == nums.length) {\n            ans.add(new ArrayList<>(subset)); // make a copy\n            return;\n        }\n        // 不选 index 位置的数\n        findSubsets(nums, index + 1);\n        subset.add(nums[index]);\n        // 选 index 位置的数\n        findSubsets(nums, index + 1);\n        // 恢复现场，防止一次递归结束，subset 被上一次递归污染\n        subset.remove(subset.size() - 1);\n    }\n\n    private List<List<Integer>> ans = new ArrayList<>();\n    private List<Integer> subset = new ArrayList<>();\n\n}\n"
  },
  {
    "path": "practice/src/io/gkd/lectures/lecture05/Lc094_InOrderTraversal.java",
    "content": "package io.gkd.lectures.lecture05;\n\nimport io.gkd.TreeNode;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class Lc094_InOrderTraversal {\n\n    private List<Integer> list = new ArrayList<>();\n\n    public List<Integer> inorderTraversal(TreeNode root) {\n        find(root);\n        return list;\n    }\n\n    public void find(TreeNode root) {\n        if (root == null) return;\n        find(root.left);\n        list.add(root.val);\n        find(root.right);\n    }\n\n}\n"
  },
  {
    "path": "practice/src/io/gkd/lectures/lecture05/Lc105_BuildTree.java",
    "content": "package io.gkd.lectures.lecture05;\n\nimport io.gkd.TreeNode;\n\n/**\n * Medium\n * 105. https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/\n *\n * preorder [3 | 9 ｜ 20 15 7] 找到了 root, 但是不确定左右子树的大小 [l1, r1]\n * inorder  [9 | 3 ｜ 15 20 7] 知道 root，自然知道了左右子树的大小   [l2, r2]. 左子树大小 = mid - l2\n *           l2  mid        r2\n *\n *          3\n *         / \\\n *       [9] [20 15 7]  preorer\n *       [9] [15 20 7]  inorer\n *      left   right\n */\npublic class Lc105_BuildTree {\n    public TreeNode buildTree(int[] preorder, int[] inorder) {\n        return build(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1);\n    }\n\n    private TreeNode build(int[] preorder, int l1, int r1, int[] inorder, int l2, int r2) {\n        if (l1 > r1) return null;\n        TreeNode root = new TreeNode(preorder[l1]);\n        // 通过找到 root 在 inorder 中的位置，确定左右子树的大小\n        int mid = l2;\n        while (inorder[mid] != root.val) mid++;\n        int leftSize = mid - l2;\n        root.left = build(preorder, l1 + 1, l1 + leftSize, inorder, l2, mid - 1);\n        root.right = build(preorder, l1 + leftSize + 1, r1, inorder, mid + 1, r2);\n        return root;\n    }\n}\n\n"
  },
  {
    "path": "practice/src/io/gkd/lectures/lecture05/Lc236_LCA.java",
    "content": "package io.gkd.lectures.lecture05;\n\nimport io.gkd.TreeNode;\n\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Map;\nimport java.util.Set;\n\n/**\n * Medium\n * 236.https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree/\n *\n * 向上标记法\n */\npublic class Lc236_LCA {\n\n    // 存储每个节点的 father\n    private Map<Integer, TreeNode> father;\n\n    // Time: O(n)\n    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {\n        this.father = new HashMap<>();     // TreeNode.val -> root TreeNode\n        calcFather(root);\n        // 存储其中一个节点的所有祖先\n        Set<TreeNode> redNodes = new HashSet<>();\n        redNodes.add(root);\n        // 记录从 p 向上的所有祖先，标记为红色\n        while(p != root) {\n            redNodes.add(p);\n            p = father.get(p.val);\n        }\n        // 在 p 的祖先中找到距离 q 最近的祖先，即 q 向上走，走到距离最近的一个红点\n        while (!redNodes.contains(q)) {\n            q = father.get(q.val);\n        }\n        return q;\n    }\n\n    // 深度优先遍历记录每个节点的父节点\n    private void calcFather(TreeNode root) {\n        if (root == null) return;\n        if (root.left != null) {\n            father.put(root.left.val, root);\n            calcFather(root.left);\n        }\n        if (root.right != null) {\n            father.put(root.right.val, root);\n            calcFather(root.right);\n        }\n    }\n}\n"
  },
  {
    "path": "practice/src/io/gkd/lectures/lecture05/Lc297_Codec.java",
    "content": "package io.gkd.lectures.lecture05;\n\nimport io.gkd.TreeNode;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\n/**\n * Hard\n * 297. https://leetcode-cn.com/problems/serialize-and-deserialize-binary-tree/\n */\npublic class Lc297_Codec {\n\n    // deserialized string list\n    private List<String> seq = new ArrayList<>();\n    // deserialized string list pointer\n    private int curr;\n\n    // Encodes a tree to a single string.\n    // 1 2 null null 3 4 null null 5 null null\n    public String serialize(TreeNode root) {\n        traverse(root);\n        return String.join(\" \", seq);\n    }\n\n    // Decodes your encoded data to tree.\n    public TreeNode deserialize(String data) {\n        seq = Arrays.asList(data.split(\" \"));\n        curr = 0;\n        return calc();\n    }\n\n    private TreeNode calc() {\n        if (seq.get(curr).equals(\"null\")) {\n            curr++;\n            return null;\n        }\n        TreeNode root = new TreeNode(Integer.parseInt(seq.get(curr)));\n        curr++;\n        root.left = calc();\n        root.right = calc();\n        return root;\n    }\n\n    private void traverse(TreeNode root) {\n        // for judge leaf node\n        if (root == null) {\n            seq.add(\"null\");\n            return;\n        }\n        seq.add(Integer.toString(root.val));\n        traverse(root.left);\n        traverse(root.right);\n    }\n}\n"
  },
  {
    "path": "practice/src/io/gkd/lectures/lecture05/Lc429_LevelOrderNTree.java",
    "content": "package io.gkd.lectures.lecture05;\n\nimport io.gkd.Node;\n\nimport java.util.ArrayList;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Queue;\n\n/**\n * Medium\n * 429. https://leetcode-cn.com/problems/n-ary-tree-level-order-traversal/\n */\npublic class Lc429_LevelOrderNTree {\n\n    public List<List<Integer>> levelOrder(Node root) {\n        // result: [[1], [3, 2, 4], [5, 6]]\n        List<List<Integer>> result = new ArrayList<>();\n        if (root == null) return result;\n        // Queue: Node - depth\n        Queue<Pair<Node, Integer>> q = new LinkedList<>();\n        // Put root in Queue\n        q.add(new Pair<Node, Integer>(root, 0));\n        while (!q.isEmpty()) {\n            Pair<Node, Integer> pair = q.poll();\n            Node node = pair.getKey();\n            int depth = pair.getValue();\n            // initialize a list in every depth(0...)\n            if (result.size() <= depth) {\n                result.add(new ArrayList<Integer>());\n            }\n            result.get(depth).add(node.val);\n            for (Node child : node.children) {\n                q.add(new Pair<>(child, depth + 1));\n            }\n        }\n        return result;\n    }\n\n    static class Pair<K, V> {\n\n        public K key;\n        public V value;\n\n        public Pair(K key, V value) {\n            this.key = key;\n            this.value = value;\n        }\n\n        public K getKey() {\n            return key;\n        }\n\n        public V getValue() {\n            return value;\n        }\n    }\n}\n"
  },
  {
    "path": "practice/src/io/gkd/lectures/lecture05/Lc589_PreOrderNTree.java",
    "content": "package io.gkd.lectures.lecture05;\n\nimport io.gkd.Node;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Stack;\n\n/**\n * Easy\n * 589. https://leetcode-cn.com/problems/n-ary-tree-preorder-traversal/\n */\npublic class Lc589_PreOrderNTree {\n    private List<Integer> list = new ArrayList<>();\n\n    public List<Integer> preorder(Node root) {\n        find(root);\n        return list;\n    }\n\n    private void find(Node root) {\n        if (root == null) return;\n        list.add(root.val);\n        for (Node node : root.children) {\n            find(node);\n        }\n    }\n\n    public List<Integer> preorderIter(Node root) {\n        List<Integer> list = new ArrayList<>();\n        if (root == null) return list;\n        Stack<Node> stack = new Stack<>();\n        stack.push(root);\n        while(!stack.isEmpty()) {\n            Node r = stack.pop();\n            list.add(r.val);\n            List<Node> children = r.children;\n            for (int i = children.size() - 1; i >= 0; i--) {\n                stack.push(children.get(i));\n            }\n        }\n        return list;\n    }\n}\n"
  },
  {
    "path": "practice/src/io/gkd/week01/Lc021_MergeTwoLists.java",
    "content": "package io.gkd.week01;\n\nimport io.gkd.ListNode;\n\n/**\n * Easy\n * 21. https://leetcode-cn.com/problems/merge-two-sorted-lists/\n */\npublic class Lc021_MergeTwoLists {\n\n    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {\n        ListNode sentinel = new ListNode();\n        ListNode cur = sentinel;\n        while (l1 != null && l2 != null) {\n            if (l1.val <= l2.val) {\n                cur.next = l1;\n                l1 = l1.next;\n            } else {\n                cur.next = l2;\n                l2 = l2.next;\n            }\n            cur = cur.next;\n        }\n        if (l1 != null) {\n            cur.next = l1;\n        } else {\n            cur.next = l2;\n        }\n        return sentinel.next;\n    }\n}\n"
  },
  {
    "path": "practice/src/io/gkd/week01/Lc066_PlusOne.java",
    "content": "package io.gkd.week01;\n\n/**\n * Easy\n * 66. https://leetcode-cn.com/problems/plus-one/submissions/\n */\npublic class Lc066_PlusOne {\n\n    public int[] plusOne(int[] digits) {\n        for (int i = digits.length - 1; i >= 0; i--) {\n            digits[i] = (digits[i] + 1) % 10;\n            if (digits[i] != 0) {\n                return digits;\n            }\n        }\n        int[] res = new int[digits.length + 1];\n        res[0] = 1;\n        return res;\n    }\n\n}\n"
  },
  {
    "path": "practice/src/io/gkd/week02/Lc146_LRUCache.java",
    "content": "package io.gkd.week02;\n\nimport java.util.HashMap;\n\n/**\n * Medium\n * 146. https://leetcode-cn.com/problems/lru-cache/\n * Time: put、get: O(1)\n * Space: O(capacity)\n */\npublic class Lc146_LRUCache {\n    // key - Node\n    HashMap<Integer, Node> cache;\n    int capacity;\n    // sentinel head\n    Node head;\n    // sentinel tail\n    Node tail;\n\n    public Lc146_LRUCache(int capacity) {\n        this.capacity = capacity;\n        this.cache = new HashMap<>();\n        this.head = new Node();\n        this.tail = new Node();\n        // Doubly Linked List: head - tail\n        this.head.next = this.tail;\n        this.tail.pre = this.head;\n    }\n\n    public int get(int key) {\n        Node node = this.cache.get(key);\n        if (node == null) {\n            return -1;\n        }\n        removeNode(node);\n        addToHead(node);\n        return node.val;\n    }\n\n    // head -> latest -> ... -> oldest -> tail\n    // head -> 1 -> 2 -> tail\n    public void put(int key, int value) {\n        if (cache.containsKey(key)) {\n            removeNode(cache.get(key));\n        }\n        Node node = new Node(key, value);\n        addToHead(node);\n        this.cache.put(key, node);\n        if (this.cache.size() > capacity) {\n            Node oldestNode = tail.pre;\n            removeNode(oldestNode);\n            this.cache.remove(oldestNode.key);\n        }\n    }\n\n    // O(1)\n    private void addToHead(Node node) {\n        // node - head.next\n        node.next = this.head.next;\n        this.head.next.pre = node;\n        // head - node\n        node.pre = this.head;\n        this.head.next = node;\n    }\n\n    // O(1)\n    private void removeNode(Node node) {\n        node.pre.next = node.next;\n        node.next.pre = node.pre;\n    }\n\n    static class Node {\n        public int key;\n        public int val;\n        public Node pre;\n        public Node next;\n\n        public Node() {}\n\n        public Node(int key, int val) {\n            this.key = key;\n            this.val = val;\n        }\n    }\n}\n"
  },
  {
    "path": "practice/src/io/gkd/week02/Lc697_FindShortestSubArray.java",
    "content": "package io.gkd.week02;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\n/**\n * Easy\n * 697. https://leetcode-cn.com/problems/degree-of-an-array/\n */\npublic class Lc697_FindShortestSubArray {\n    public int findShortestSubArray(int[] nums) {\n        // map:\n        // key - element\n        // value - value[]\n        // - value[0]: element count;\n        // - value[1]: first element index;\n        // - value[2]: last element index\n        HashMap<Integer, int[]> map = new HashMap<>();\n        int degree = 0;\n        for (int i = 0; i < nums.length; i++) {\n            int element = nums[i];\n            if (map.containsKey(element)) {\n                int[] value = map.get(element);\n                value[0]++;\n                value[2] = i;\n                degree = Math.max(degree, value[0]);\n            } else {\n                map.put(element, new int[] {1, i, i});\n                degree = Math.max(degree, 1);\n            }\n        }\n        // System.out.println(degree);\n        int shortestSubArrayLen = 50000;\n        for (Map.Entry<Integer, int[]> entry : map.entrySet()) {\n            int[] value = entry.getValue();\n            if (degree == value[0]) {\n                shortestSubArrayLen = Math.min(shortestSubArrayLen, value[2] - value[1] + 1);\n            }\n        }\n        return shortestSubArrayLen;\n    }\n}\n"
  },
  {
    "path": "practice/src/io/gkd/week03/Lc106_BuildTree.java",
    "content": "package io.gkd.week03;\n\nimport io.gkd.TreeNode;\n\n/**\n * Medium\n * 106. https://leetcode-cn.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/\n *\n * postorder   [9 | 15 7 20 | 3]\n * inorder     [9 | 3 | 15 20 7]\n *              l1  mid       r1\n *             3\n *            / \\\n *          [9] [15 7 20]\n *          [9] [15 20 7]\n */\npublic class Lc106_BuildTree {\n    public TreeNode buildTree(int[] inorder, int[] postorder) {\n        return build(inorder, 0, inorder.length, postorder, 0, postorder.length - 1);\n    }\n\n    private TreeNode build(int[] inorder, int l1, int r1, int[] postorder, int l2, int r2) {\n        if (l2 > r2) return null;\n        TreeNode root = new TreeNode(postorder[r2]);\n        int mid = l1;\n        while (inorder[mid] != root.val) mid++;\n        int leftSize = mid - l1;\n        root.left = build(inorder, l1, mid - 1, postorder, l2, l2 + leftSize - 1);\n        root.right = build(inorder, mid + 1, r1, postorder, l2 + leftSize, r2 - 1);\n        return root;\n    }\n}\n"
  },
  {
    "path": "practice/src/io/gkd/week03/Lc210_FindOrder2.java",
    "content": "package io.gkd.week03;\n\nimport java.util.LinkedList;\nimport java.util.Queue;\n\npublic class Lc210_FindOrder2 {\n    public int[] findOrder(int numCourses, int[][] prerequisites) {\n        if (numCourses == 0) return new int[0];\n        int[] inDegrees = new int[numCourses];\n        // 建立入度表\n        // 对于有先修课的课程，计算有几门先修课\n        for (int[] p : prerequisites) {\n            inDegrees[p[0]]++;\n        }\n        // 入度为0的节点队列\n        Queue<Integer> queue = new LinkedList<>();\n        for (int i = 0; i < inDegrees.length; i++) {\n            if (inDegrees[i] == 0) queue.offer(i);\n        }\n        int count = 0;  // 记录可以学完的课程数量\n        int[] res = new int[numCourses];  // 可以学完的课程\n        // 根据提供的先修课列表，删除入度为 0 的节点\n        while (!queue.isEmpty()){\n            int curr = queue.poll();\n            res[count++] = curr;   // 将可以学完的课程加入结果当中\n            for (int[] p : prerequisites) {\n                if (p[1] == curr){\n                    inDegrees[p[0]]--;\n                    if (inDegrees[p[0]] == 0) queue.offer(p[0]);\n                }\n            }\n        }\n        if (count == numCourses) return res;\n        return new int[0];\n    }\n}\n"
  },
  {
    "path": "practice/src/io/gkd/week03/NOTES.md",
    "content": "# 本周总结\n\n本周主要理解了树的相关内容，图的内容还在学习中。\n\n## 树\n\n* 树的定义\n* 二叉树\n    * 完全二叉树\n    * 满二叉树\n* 二（多）叉树的遍历\n* 基环树\n\n## 图\n\n* 链表、树、基环树、图的关系\n* 图的表示\n* 图的遍历\n\n\n\n"
  },
  {
    "path": "questions/questions.md",
    "content": "# Questions\n\n## 数组\n\n### 1. 数组与泛型动态数组\n[[Solution1](https://github.com/guokaide/algorithm/blob/master/summary/algorithm.md)][[Solution2](https://github.com/guokaide/algorithm/blob/master/algorithms/src/array/GenericArray.java)]请谈谈数组的特点，并且实现泛型动态数组（即Vector in C++ or ArrayList in Java）的插入、删除以及查找操作，比较原生数组与泛型动态数组的区别。查看泛型动态数组API:\n\n```java\npackage array;\n   \n   /**\n    * 泛型动态数组\n    *\n    * @param <T>\n    */\n   \n   public class GenericArray<T> {\n       private T[] data;\n       private int size;\n   \n       // 根据传入容量，构造Array\n       public GenericArray(int capacity) {\n           data = (T[]) new Object[capacity];\n           size = 0;\n       }\n   \n       // 无参构造方法，默认数组容量为10\n       public GenericArray() {\n           this(10);\n       }\n   \n       // 获取数组容量\n       public int getCapacity() {\n   \n       }\n   \n       // 获取当前元素个数\n       public int count() {\n   \n       }\n   \n       // 判断数组是否为空\n       public boolean isEmpty() {\n   \n       }\n   \n       // 修改 index 位置的元素\n       public void set(int index, T e) {\n   \n       }\n   \n       // 获取对应 index 位置的元素\n       public T get(int index) {\n   \n       }\n   \n       // 查看数组是否包含元素e\n       public boolean contains(T e) {\n   \n       }\n   \n       // 获取对应元素的下标, 未找到，返回 -1\n       public int find(T e) {\n   \n       }\n   \n   \n       // 在 index 位置，插入元素e, 时间复杂度 O(m+n)\n       public void add(int index, T e) {\n   \n       }\n   \n       // 向数组头插入元素\n       public void addFirst(T e) {\n   \n       }\n   \n       // 向数组尾插入元素\n       public void addLast(T e) {\n   \n       }\n   \n       // 删除 index 位置的元素，并返回\n       public T remove(int index) {\n   \n       }\n   \n       // 删除第一个元素\n       public T removeFirst() {\n   \n       }\n   \n       // 删除末尾元素\n       public T removeLast() {\n   \n       }\n   \n       // 从数组中删除指定元素\n       public void removeElement(T e) {\n   \n       }\n   \n       @Override\n       public String toString() {\n           StringBuilder builder = new StringBuilder();\n           builder.append(String.format(\"Array size = %d, capacity = %d \\n\", size, data.length));\n           builder.append('[');\n           for (int i = 0; i < size; i++) {\n               builder.append(data[i]);\n               if (i != size - 1) {\n                   builder.append(\", \");\n               }\n           }\n           builder.append(']');\n           return builder.toString();\n       }\n   \n   \n       // 扩容方法，时间复杂度 O(n)\n       private void resize(int capacity) {\n   \n       }\n   \n       private void checkIndex(int index) {\n           if (index < 0 || index > size) {\n               throw new IllegalArgumentException(\"Add failed! Require index >=0 and index <= size.\");\n           }\n       }\n       \n       private void checkIndexForRemove(int index) {\n           if (index < 0 || index >= size) {\n               throw new IllegalArgumentException(\"Remove failed! Require index >= 0 and index < size.\");\n           }\n       }\n   }\n   \n```\n\n### 2. 1000万整数中查找某个数\n[[Solution](https://github.com/guokaide/algorithm/blob/master/summary/algorithm.md#%E9%97%AE%E9%A2%98)]假设我们有 1000 万个整数数据，每个数据占 8 个字节，如何设计数据结构和算法，快速判断某个整数是否出现在这 1000 万数据中？ 我们希望这个功能不要占用太多的内存空间，最多不要超过 100MB，你会怎么做呢？\n\n### 3. 约瑟夫问题\n [[Solution](https://github.com/guokaide/algorithm/blob/master/algorithms/src/joseph/Joseph.java)]0,1,...,n-1这n个数字排成一个圆圈，从数字0开始，每次从这个圆圈里删除第m个数字。求这个圆圈里剩下的最后一个数字。\n\n\n\n\n## 链表\n\n### 1. 链表与数组\n[[Solution1](https://github.com/guokaide/algorithm/blob/master/summary/algorithm.md)][[Solution2](https://github.com/guokaide/algorithm/blob/master/algorithms/src/linkedlist/SingleLinkedList.java)]请谈谈链表的特点，比较数组与链表的不同，并实现单链表的基本操作：插入、删除以及查找操作。查看单链表API：\n\n   ```java\n   package linkedlist;\n   \n   /**\n    * 1）单链表的插入、删除、查找操作；\n    * 2）链表中存储的是int类型的数据；\n    *\n    */\n   public class SingleLinkedList {\n   \n     private Node head = null;\n   \n     public Node findByValue(int value) {\n   \n     }\n   \n     public Node findByIndex(int index) {\n   \n     }\n   \n     public void insertToHead(int value) {\n   \n     }\n   \n     public void insertToHead(Node newNode) {\n   \n     }\n       \n     public void insertToTail(int value) {\n           \n     }\n       \n     public void insertToTail(Node newNode) {\n           \n     }\n   \n     public void insertAfter(Node p, int value) {\n   \n     }\n   \n     public void insertAfter(Node p, Node newNode) {\n   \n     }\n   \n     public void insertBefore(Node p, int value) {\n   \n     }\n   \n     public void insertBefore(Node p, Node newNode) {\n       \n     }\n   \n     public void deleteByNode(Node p) {\n       \n     }\n   \n     public void deleteByValue(int value) {\n       \n     }\n   \n     public void printAll() {\n       \n     }\n   \n     public static Node createNode(int value) {\n       return new Node(value, null);\n     }\n   \n     public static class Node {\n       private int data;\n       private Node next;\n   \n       public Node(int data, Node next) {\n         this.data = data;\n         this.next = next;\n       }\n   \n       public int getData() {\n         return data;\n       }\n     }\n   \n   }\n   ```\n\n### 2. Reverse Linked List\n\n[[Solution](https://github.com/guokaide/algorithm/tree/master/leetcode/src/reverselinkedlist_206)][206.Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/description/)\n\n\n\n### 3. Middle of the Linked List\n\n[[Solution](https://github.com/guokaide/algorithm/blob/master/algorithms/src/linkedlist/FindMidNode.java)]给定一个单链表，请找到其中间节点。例如：1->2->3, 中间节点为2; 1->2->3->4, 中间节点为3。\n\n或者 leetcode版本：[876.Middle of the Linked List ](https://leetcode.com/problems/middle-of-the-linked-list/ )\n\n\n### 4. LRU Cache\n\n[[Solution](https://github.com/guokaide/algorithm/blob/master/algorithms/src/lru/LRU.java)][146.LRU Cache](https://leetcode.com/problems/lru-cache/description/)\n\n\n### 5. Palindrome Linked List\n\n[[Solution](https://github.com/guokaide/algorithm/blob/master/leetcode/src/palindromelinkedlist_234/PalindromeLinkedList.java)]如果一个字符串是通过单链表来存储的，该如何来判断是一个回文串呢？其时间复杂度和空间复杂度是多少？或者leetcode版本：[234.Palindrome Linked List ](https://leetcode.com/problems/palindrome-linked-list/ )\n\n### 6. Linked List Cycle\n\n[[Solution](https://github.com/guokaide/algorithm/blob/master/leetcode/src/linkedlistcycle_141/LinkedListCycle.java)][141. Linked List Cycle](https://leetcode.com/problems/linked-list-cycle/ )\n\n\n\n### 7. Merge Two Sorted Lists\n\n[[Solution](https://github.com/guokaide/algorithm/blob/master/leetcode/src/mergetwosortedlist_21/Merge2SortedLists.java)][21. Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/ )\n\n\n\n### 8. Remove Nth Node From End of List\n\n[[Solution](https://github.com/guokaide/algorithm/blob/master/leetcode/src/removenthnodefromendoflist_19/RemoveNthNodeFromEndOfList.java)][19. Remove Nth Node From End of List ](https://leetcode.com/problems/remove-nth-node-from-end-of-list/ )\n\n\n\n## 栈\n\n### 1. Implement Stack using Array\n\n[[Solution](https://github.com/guokaide/algorithm/blob/master/algorithms/src/stack/ArrayStack.java)] 实现顺序栈。**顺序栈**：用数组实现的栈。栈的API如下：\n\n```java\npublic class ArrayStack {\n    public boolean push(int item) {\n        \n    }\n    \n    public int pop() {\n        \n    }\n}\n```\n\n**扩展问题：**\n\n[[Solution](https://github.com/guokaide/algorithm/blob/master/algorithms/src/stack/DynamicArrayStack.java)]你是否能够实现支持动态扩容的顺序栈？是否能够分析其操作的时间复杂度？（动态扩容的实现方法见问题【数组-1.数组与泛型动态数组】）\n\n### 2. Implement Stack using Linked List\n\n[[Solution](https://github.com/guokaide/algorithm/blob/master/algorithms/src/stack/ListStack.java)] 实现链式栈。**链式栈**：用链表实现的栈。栈的API如下：\n\n```java\npublic class ListStack {\n    public boolean push(int item) {\n        \n    }\n    \n    public int pop() {\n        \n    }\n}\n```\n\n\n\n### 3. Implement Stack using Queues\n\n[Solution][225. Implement Stack using Queues](https://leetcode.com/problems/implement-stack-using-queues/)\n\n\n\n### 4. Implement Queue using Stacks\n\n[Solution][232. Implement Queue using Stacks](https://leetcode.com/problems/implement-queue-using-stacks/)\n\n\n\n### 5. Valid Parentheses\n\n[Solution][20. Valid Parentheses](https://leetcode.com/problems/valid-parentheses/)\n\n\n\n### 6. Min Stack\n\n[Solution][155. Min Stack](https://leetcode.com/problems/min-stack/)\n\n \n\n### 7. Implement the Forward and Backward Functions of the Browser\n\n[Solution] 浏览器的前进和后退功能：当你依次访问完一串页面 a-b-c 之后，点击浏览器的后退按钮，就可以查看之前浏览过的页面 b 和 a。当你后退到页面a，点击前进按钮，就可以重新查看页面 b 和 c。但是，如果你后退到页面 b 后，点击了新的页面 d，那就无法再通过前进、后退功能查看页面 c 了。请实现这个功能。\n\n\n\n## 队列\n\n### 1. Implement Queue using Array\n\n[[Solution](https://github.com/guokaide/algorithm/blob/master/algorithms/src/queue/ArrayQueue.java)] 实现顺序队列。**顺序队列**：用数组实现的队列。API如下：\n\n```java\npublic class ArrayQueue {\n    public boolean enqueue(int Item) {\n        \n    }\n    \n    public int dequeue() {\n        \n    }\n}\n```\n\n\n\n### 2. Implement Queue using Linked List\n\n[[Solution](https://github.com/guokaide/algorithm/blob/master/algorithms/src/queue/ListQueue.java)] 实现链式队列。**链式队列**：用链表实现的队列。API如下：\n\n```java\npublic class ListQueue {\n    public boolean enqueue(int Item) {\n        \n    }\n    \n    public int dequeue() {\n        \n    }\n}\n```\n\n\n\n### 3. Design Circular Queue\n\n[Solution][622. Design Circular Queue](https://leetcode.com/problems/design-circular-queue/)\n\n\n\n### 4. Design Circular Deque\n\n[Solution][641. Design Circular Deque](https://leetcode.com/problems/design-circular-deque/)\n\n\n\n## 二分查找算法\n\n### 1. 二分查找算法\n\n[[Solution](https://github.com/guokaide/algorithm/blob/master/algorithms/src/array/BinarySearch.java)] 请实现正确的二分查找算法（递归与非递归），并分析其时间复杂度（O(nlogn)）。\n\n### 2. 二分查找算法变形问题\n\n[[Solution](https://github.com/guokaide/algorithm/blob/master/algorithms/src/array/BinarySearch.java)] 给定一个有序数组，\n\n- 查找第一个值等于给定值的元素\n- 查找最后一个值等于给定值的元素\n- 查找第一个大于等于给定值的元素\n- 查找最后一个小于等于给定值的元素\n\n### 3. 旋转数组中的最小值\n\n[[Solution](https://github.com/guokaide/algorithm/blob/master/algorithms/src/array/MinNumberInRotatedArray.java)] 数组的旋转：将一个数组最开始的若干个元素搬到数组的末尾，即为数组的旋转。输入一个递增排序的数组的一个旋转，数组旋转数组的最小值。例如，数组{3,4,5,1,2}是数组{1,2,3,4,5}的一个旋转，该数组的最小值为1。要求时间复杂度为O(logn)。\n\n### 4. Sqrt(x)\n\n[Solution][69. Sqrt(x)](https://leetcode.com/problems/sqrtx/description/)\n\n\n\n## 递归\n### 1. Pow(x, n)\n[Solution][50. Pow(x,n)](https://leetcode.com/problems/powx-n/description/)\n"
  },
  {
    "path": "solutions/剑指offer 题解.md",
    "content": "# 剑指offer 题解\n\n## 2. 实现单例模式\n\n### 什么是单例模式？\n\n**单例模式**，顾名思义就是整个系统只能有1个实例存在，不能再多了。\n\n### 单例模式的好处\n\n单例模式适用于应用中频繁创建的对象，尤其是频繁创建的重量级对象。\n例如统一的配置文件。\n使用单例模式能够提升性能，减小内存开销。\n\n### 单例模式的实现\n\n#### 0. 概述\n\n如何实现一个单例模式呢？我们讨论一下这个过程。\n\n首先我们搞一个类出来：\n\n```java\npublic class Singleton {\n    \n}\n```\n\n空空如也，非常好，但是有个问题，大家可以在外面随便`new Singleton()`,那系统里就不止一个Singleton实例了，因此需要我们阻挡`new Singleton()`。那就不写构造方法呗？当然不行。因为如果不写构造方法，系统会默认分配无参构造器。那就直接将构造方法改为`private`呗。\n\n```java\npublic class Singleton {\n    private Singleton() {}\n}\n```\n\n好，既然外面造不出Singleton实例了，那就自己造呗。\n\n```java\npublic class Singleton {\n    private static final Singleton instance = new Singleton();\n    private Singleton() {}\n}\n```\n\n`private`关键字保证了Singleton实例的私有性，不可见性，不可访问性；`static`关键字保证了Singleton实例的静态性，与类同在，不依赖于类的实例化就在内存中永生；`final`关键字保证这个实例是常量，不可修改。\n\n那么既然外部无法创造这个实例，如何获取这个实例呢？整个`getInstance()`静态方法在外部获取这个实例，而且这个方法必须是`public`的。\n\n```java\npublic class Singleton {\n    private static final Singleton instance = new Singleton();\n    private Singleton() {}\n    public static Singleton getInstance() {\n        return instance;\n    } \n}\n```\n\n到此，外部就可以通过`Singleton.getInstance()`获取这个单例。\n\n这就是一个简单的**单例模式**的雏形（这其实是一个饿汉式单例模式）。以下介绍几种面试中常见的单例模式实现。\n\n#### 1.饿汉式\n饿汉式加载类的时候，就会创建类的实例对象，那么如果不用这个单例的话，就会消耗内存，浪费性能。\n因此，需要懒加载（lazy-load），即延迟加载。\n\n```java\npublic class Singleton {\n    // instance必须是static变量（类变量）\n    private static Singleton instance = new Singleton();\n\n    // private无参构造函数: Java会自动为没有明确声明构造函数的类，\n    // 定义一个public的无参构造函数，若没有这个private无参构造函数，\n    // 外部可以随意new Singleton\n    private Singleton() {}\n\n    // getInstance必须是static方法（类方法）\n    public static Singleton getInstance() {\n        return instance;\n    }\n}\n```\n\n#### 2.懒汉式\n懒汉式改进了饿汉式的性能问题，但是又带来了一个问题，即线程安全问题。\n在多线程的情况下，会出现多个实例，违背了单例模式的原则。\n\n```java\npublic class Singleton {\n    private static Singleton instance = null;\n\n    private Singleton() {}\n\n    public static Singleton getInstance() {\n        if (instance == null) {\n            instance = new Singleton();\n        }\n\n        return instance;\n    }\n}\n```\n\n#### 3.双重校验（双检锁）\n双重校验能够保证单例模式的实例唯一性，同时能够兼顾效率和线程安全。\n\n```java\npublic class Singleton {\n    // volatile提供可见性（工作内存的值能立即在主内存中可见），\n    // 保证getInstance返回的是初始化完全的对象\n    private static volatile Singleton instance = null;\n\n    private Singleton() {}\n\n    public static Singleton getInstance() {\n        // 同步之前进行null检查，避免进入代价相对昂贵的同步块\n        if (instance == null) {\n            synchronized (Singleton.class) {\n                // 持有锁之后进行null检查，避免上一个线程已经初始化变量\n                if (instance == null) {\n                    instance = new Singleton();\n                }\n            }\n        }\n        return instance;\n    }\n}\n```\n\n#### 4.静态内部类\n静态内部类的方式实现，可以保证多线程对象的唯一性，同时可以降低双重校验中同步锁机制的代价。\n这种方式还有个好处，就是静态内部类不会在单例类加载的时候就加载，而是在调用`getInstance()`\n方法时才加载。\n\n```java\npublic class Singleton {\n    private static class SingletonHolder {\n        public static Singleton instance = new Singleton();\n    }\n\n    public static Singleton getInstance() {\n        return SingletonHolder.instance;\n    }\n}\n```\n\n####  5.枚举方法 \n枚举方法是由《Effective Java》的作者Josh Bloch提出，其好处在于：\n* 自由序列化\n* 保证只有一个实例\n* 线程安全\n\n```java\npublic enum Singleton {\n    INSTANCE;\n\n    private int id;\n\n    public int getId() {\n        return id;\n    }\n\n    public void setId(int id) {\n        this.id = id;\n    }\n\n    public static void main(String[] args) {\n        //调用\n        Singleton.INSTANCE.setId(1);\n        Singleton.INSTANCE.getId();\n    }\n}\n```\n\n\n\n## 3. 数组中重复的数字\n\n### 3.1 找出数组中重复的数字\n\n在一个长度为n的数组里的所有的数字都在0~n-1的范围内。数组中某些数字是重复的，但不知道有几个数字重复，也不知道每个数字重复了几次。请找出数组中任意的一个数字。\n\n例如，输入长度为7的数组{2,3,1,0,2,5,3}，那么对应输出的是重复数字2或者3。\n\n[nowcoder](https://www.nowcoder.com/practice/623a5ac0ea5b4e5f95552655361ae0a8?tpId=13&tqId=11203&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking)\n\n**Solution**\n\n1.遍历数组，同时使用HashMap记录数组中每个元素出现的个数，当某个元素个数大于1时，输出该元素即可。\n\n时间复杂度O(n)，空间复杂度O(n)。\n\n实现如下：\n\n```java\npublic boolean duplicate(int numbers[], int [] duplication) {\n        if (numbers == null || numbers.length < 2) {\n            return false;\n        }\n\n        HashMap<Integer, Integer> map = new HashMap<>();\n        for (int i = 0; i < numbers.length; i++) {\n            if (!map.containsKey(numbers[i])) {\n                map.put(numbers[i], 1);\n            } else {\n                duplication[0] = numbers[i];\n                return true;\n            }\n        }\n        return false;\n}\n```\n\n2.方法1并未使用题目中数组(numbers)元素都在0~n-1这个条件，如果使用这个条件的话，会发现若数组中没有重复元素的话，那么长度为n的数组，排序之后，应该是{0,1,2，...，n-1}，即k位置的元素为k。若有重复元素的话，那么k位置元素为k，其他位置也可能有k。利用这个特征遍历数组，若k位置的值为k，则遍历下一个元素；若k位置的元素的值不是k，则将k位置元素与numbers[k]位置元素交换，直到k位置的元素为k，然后遍历下一个元素，若在交换的过程中，发现k位置的元素等于numbers[k]位置的值，则k就是所求重复的值，结束遍历。\n\n时间复杂度O(n)，空间复杂度O(1)。\n\n实现如下：\n\n```java\npublic boolean duplicate(int numbers[], int [] duplication) {\n        if (numbers == null || numbers.length < 2) {\n            return false;\n        }\n\n        for (int i = 0; i < numbers.length; i++) {\n            if (numbers[i] == i) {\n                i++;\n            } else {\n                int m = numbers[i];\n                if (numbers[m] == m) {\n                    duplication[0] = m;\n                    return true;\n                } else {\n                    int tmp = numbers[i];\n                    numbers[i] = numbers[m];\n                    numbers[m] = tmp;\n                }\n            }\n        }\n        return false;\n}\n```\n\n### 3.2 不修改数组找出重复的数字\n\n在一个长度为n+1的数组里的所有的数字都在1~n的范围内，所以数组中至少有一个数字是重复的，请在不修改数组的情形下，找出数组中任意一个重复数字。\n\n例如，输入长度为8的数组{2,3,5,4,3,2,6,7}，那么对应输出的是重复数字2或者3。\n\n"
  },
  {
    "path": "summary/algorithm.md",
    "content": "# Algorithm\n\n##  数组\n\n### 数组的基本概念\n\n**数组（Array）**：数组是一种**线性表**数据结构。它用一组**连续的内存空间**，来存储一组具有**相同数据类型**的数据。\n\n* 线性表与非线性表\n  * 线性表（Linear List）：数据排成像一条线一样的结构。每个线性表上的数据最多只有前和后2个方向。如：数组、链表、队列、栈等。\n  * 非线性表：数据之间不是简单的前后关系。如：二叉树、堆、图等。\n* 连续的内存空间和相同类型的数据\n  * 正是因为这2个限制，数组具有一个杀手级的特性：**随机访问**。即其根据下标随机访问的时间复杂度为O(1)。但是要**注意**数组中查找一个元素的时间复杂度不是O(1)。\n  * 但是也正是因为数组存储需要连续的内存空间，因此其插入和删除操作非常低效，因为为了保证数组数据的连续性，需要做大量的数据搬移工作。\n\n### 数组的基本操作\n\n* 插入：\n  * 实现：将某个元素插入到数组第k个位置，需要将k~n部分的元素向后搬移一位，然后插入元素。若插入到数组的末尾，时间复杂度O(1)；插入到数组的开头，时间复杂度O(n)；插入的平均时间复杂度为（1+2+...+n）/n = O(n)。注意这个实现针对的数组是有序的。\n  * **优化**：若数组只是一个存储数据的集合，其元素是无序的，则插入时不需要搬移数据。此时若想将某个元素插入到数组第k个位置，首先将该位置的元素移动到数组末尾，然后将待插入元素插入到第k个位置，时间复杂度降为O(1)。但是要注意这个优化是针对数组是无序的,这个优化其实是放弃了数组逻辑上的连续。\n* 删除\n  * 实现：若要删除第k个位置的元素，则需要将k+1~n个元素向前搬移一位。若删除数组的末尾，时间复杂度O(1)；删除数组的开头，时间复杂度O(n)；删除平均时间复杂度为 O(n)。\n  * **优化**：将多次删除一起执行。当我们要删除多个元素的时候，并不立即进行搬移操作，而是将多个元素标记为已删除，然后当数组满了的时候，将标记的元素一起删除，这样就减少了数组搬移的次数，提高了效率。这就是**JVM中标记-清除**算法的核心思想。\n* 随机访问\n  * 实现：数组的随机访问，只需要根据首地址和下标通过寻址公式计算出对应内存地址即可。\n\n### 数组的内存模型\n\n* 访问数组的本质：计算机为每一个数组分配了一段连续的内存，计算机通过访问内存的地址访问内存，因此访问数组的本质就是访问一段连续内存。对内存的要求较高。\n* 既然访问数组其实是访问一段连续内存，那么计算机就可以根据数组的首地址和下标，通过公式计算出每一个元素所在的位置。数组访问寻址公式：\n  * 给定一维数组`a[n]`, 则`a[k]`的内存地址为：`a[k]_address = base_address + k * type_size`。\n  * 给定二维数组`a[m][n]`则`a[i][j]`的内存地址为：`a[i][j]_address = base_address + (i*n + j) * type_size `。\n\n\n##  链表\n\n### 链表的基本概念\n\n**链表（Linked List）**：链表是一种**线性表**数据结构。它用一组**不连续的内存空间**，来存储一组具有**相同数据类型**的数据。\n\n\n\n### 链表的基本操作\n\n- 插入：链表的插入只需要调整前后节点的指针即可,时间复杂度为O(1)\n\n- 删除：链表的删除只需要调整前后节点的指针即可,时间复杂度为O(1)\n\n- 随机访问：链表的随机访问，无法像数组一样通过寻址公式计算出下标的内存位置，只能通过遍历找到相应的节点，时间复杂度为O(n)。\n\n\n\n### 链表的分类\n\n#### 1. 单链表\n\n结构：head ->  data -> data -> null\n\n特点：结构简单，但是随机访问某个节点时，只能从头到尾遍历，找到这个节点。\n\n\n\n#### 2. 循环链表\n\n结构：head ->  data -> data -> head\n\n特点：与单链表相比，其优势在于可以从尾到头遍历。\n\n\n\n#### 3. 双向链表\n\n结构：head <->  data <-> data -> null\n\n特点：双向链表最大的优势在于找到前驱结点的时间复杂度为O(1)，正因为这个特点，使得双向链表在某些情况下，插入、删除等操作要比单链表简单高效，尽管时间复杂度都是O(1)。这也是为什么双向链表占用的内存要高于单链表，但是日常使用中，双向链表更加常用的原因。**Java中LinkedHashMap就用双向链表来记录插入的键值对的顺序。**\n\n\n\n#### 4. 双向循环链表\n\n双向循环链表是双向链表与循环链表的组合。\n\n结构：head <->  data <-> data -> head\n\n\n\n#### 问题：为什么双向链表比单链表高效？\n\n**插入和删除**\n\n（1）删除操作\n\n在实际开发中，从链表删除一个数据主要是以下2种情况：\n\n* 删除某个“值等于给定值”的节点\n* 删除给定指针指向的节点\n\n事实上，删除操作本身的时间复杂度为O(1),单链表和双向链表的性能差别，主要在于查找的过程。\n\n对于第一种情况，无论单链表还是双向链表，无论是插入还是删除，都需要从头到尾遍历找到“值等于给定值”的节点，因此二者的时间复杂度均为O(n)。\n\n对于第二种情况，已经找到了要删除的节点（记为q），但是要删除这个节点需要知道其前驱节点(记为p)。单链表中，无法立即知道q的前驱节点p,因此只能从头遍历，直到`p->next = q`，这个过程的时间复杂度是O(n); 而双向链表要删除的节点q已经保存了前驱节点p的指针。因此可以O(1)的时间找到p。因此单链表删除操作时间复杂度为O(n)，而双向链表为O(1)。\n\n（2）插入操作\n\n分析同上。\n\n**查找**\n\n对于一个有序链表，双向链表按值查找的效率要高于单链表。因为，我们可以记录上一次查找的位置p，每次查找时，比较要查找的值与p的关系，若小于p，则向前，反之则向后，平均只需要查找一半的数据。\n\n因此，双向链表在删除和插入给定节点以及在有序链表中查找值这几种情形下，效率要高于单链表。\n\n事实上，这里的双向链表的性能来自于其对空间的牺牲，它的空间占用要高于单链表，体现了 **“空间换时间”** 的设计思想。\n\n\n#### \n\n### 数组 VS 链表\n\n**1. 内存**\n\n从内存来讲，数组要求内存是一块连续的内存空间，而链表则不需要内存空间连续，例如，如果申请一个100MB大小的数组，当内存中没有连续的大于等于100MB的内存空间时，即使内存的总空间大于100MB，内存也会申请失败；而链表则不需要连续的内存空间，链表通过指针将不同的内存块串联起来，如果内存的总空间大于100MB，那么申请100MB的链表则没有任何问题。\n\n尽管数组需要连续的内存空间，对内存的要求较高，但是正因为这个特性，数组可以借助CPU缓存机制，预读数组中的数据，因此访问效率更高。而链表由于内存不连续，因此对CPU缓存不友好，无法预读。\n\n若代码对内存使用比较苛刻，那么使用数组会比较好。因为链表的每个节点都需要使用额外的内存存储指向下一个节点的指针，额外内存高于数组。\n\n链表在进行插入和删除操作的时候，导致内存频繁的申请和释放，容易造成内存碎片。在Java中，有可能到导致频繁的GC。\n\n**2. 基本操作**\n\n| 时间复杂度 | 数组 | 链表 |\n| :--------: | :--: | :--: |\n| 插入、删除 | O(n) | O(n) |\n|  随机访问  | O(1) | O(n) |\n\n根据二者的时间复杂度，在随机访问更加频繁的场景下（插入、删除操作非常少），数组更加适用；在插入、删除操作频繁的场景下，链表更加适用。\n\n\n\n## 栈\n\n### 栈的基本概念\n\n**栈（stack）**: 栈是一种“操作受限”的**线性表**数据结构。栈元素具有后进先出，先进后出的特点。\n\n\n\n### 栈的存储\n**顺序栈**：用数组实现的栈。\n**链式栈**：用链表实现的栈。\n\n\n\n### 栈的基本操作\n\n栈具有2个基本操作：栈的插入和删除，而且只能在一端进行插入和删除操作。\n\n栈的插入和删除操作的时间复杂度为O(1)。\n\n示例：一摞叠在一起的盘子能很好地说明栈。放盘子的时候，都是从下往下一个个放；取盘子的时候，则是从上往下一个个取，不能从中间任意抽出。只涉及到了线性表一端的插入和删除。\n\n\n\n### 栈的应用\n\n**当某个数据集合只涉及在一端插入和删除数据，并且满足后进先出、先进后出的特性，那么就应该首选栈作为其数据结构。** 例如，函数调用就是依托栈实现的。\n\n\n\n## 队列\n\n### 队列的基本概念\n\n**队列（Queue）**:队列是一种“操作受限”的线性表数据结构。队列元素具有先进先出，后进后出的特点。\n\n\n\n### 队列的存储\n**顺序队列**：用数组实现的队列。\n**链式队列**：用链表实现的队列。\n\n\n\n### 队列的基本操作\n\n队列具有2个基本操作：入队和出队。\n\n队列的入队和出队的时间复杂度均为O(1)。\n\n示例：排队买票，先来的先买，后来的只能排到队尾，不能插队。\n\n\n\n### 队列的应用\n\n**阻塞队列**是在队列的基础上增加了阻塞操作。当队列为空的时候，从队头取数据会被阻塞，直到队列中存在数据的时候，才返回数据；当队列满了的时候，插入数据操作会被阻塞，直到队列中有空闲位置时再插入数据然后再返回。我们可以使用阻塞队列实现**生产者-消费者模型**。\n\n在多线程的情形下，就会存在安全问题，这就需要并发队列了。\n\n**并发队列**是指线程安全的队列。并发队列最简单的实现就是在`enqueue()`和`dequeue()`方法上加锁，但是锁的粒度比较大，因此并发度不是很好，同一时刻仅仅允许一个操作。但是，基于数组的循环队列，利用CAS原子操作，可以实现非常高效的并发队列。这也是循环队列比链式队列应用更加广泛的原因。\n\n如何实现无锁并发队列？\n\n使用数组+CAS的方式可以实现。在入队前，获取tail的位置，入队时，比较tail是否发生变化，若没有发生变化，则允许入队，反之入队失败。出队操作分析同上。\n\n\n\n**对于大部分资源有限的场景，当没有空闲资源时，基本上都可以通过队列实现请求排队。** 例如线程池，分布式应用中的消息队列（如kafka）等。\n\n\n\n**问题**：当线程池没有空闲线程时，新的任务请求线程资源时，线程池该如何处理？\n\n一般有2种策略：\n\n* 非阻塞的处理方式，直接拒绝任务请求\n* 阻塞的处理方式，将请求排队，等到有空闲线程时，取出排队的请求继续处理。\n\n那么如何存储排队的请求呢？一般希望公平的处理每个请求，因此按照先来的请求先处理，那么就适合用队列来存储请求。那么队列该如何实现呢？是基于数组还是基于链表呢？\n\n* 基于链表的实现方式，可以实现一个可以支持无限排队的**无界队列**（unbounded queue），但是可能导致多多的请求等待，请求的响应时间过长。因此，针对响应时间比较敏感的系统，基于链表实现的无界队列的线程池是不合适的。\n* 基于数组的实现方式，可以实现一个**有界队列**（bounded queue），队列大小有限，因此当请求数量超过队列大小时，接下来的请求就只能拒绝处理。这种方式适用于响应时间比较敏感的系统。队列的大小的设计就至关重要了。太大会导致等待请求太多，太小则会造成无法充分利用系统资源，发挥最大性能。\n\n\n\n\n## 二分查找\n### 二分查找 \n\n* 二分查找：高效的有序数据集合查找算法\n  * 时间复杂度：O(logn)\n  * O(logn)是一个快到很恐怖复杂度。例如：当n=2^32（约42亿）时，logn=32。即从42亿有序数据中二分查找一个数据，最多32次。相反，O(2^n)是一个慢的恐怖的时间复杂度。\n* 应用场景：\n  * 针对数组，原因是：\n    * 数组：根据下标随机访问的时间复杂度O(1)\n    * 链表：根据下标随机访问的时间复杂度O(n)\n  * 针对有序数据\n    * 二分查找只能用在插入、删除操作不频繁的静态数据中，一次排序多次查找的场景中，因为排序最快O(nlogn)\n    * 那么动态数据集合如何快速查找某个数据呢？答案是二叉树。\n  * 数据量太小不适合二分查找\n    * 数据量太小，直接顺序遍历即可，二分查找的优势并不明显\n    * 但是如果数据之间的比较操作比较耗时间，那么减少比较操作会大大提高性能，因此即使数据量小，但是二分查找可以减小比较次数，例如数组中存储的是长度超过300的字符串，这样长度的字符串的比较则会非常耗时间。\n  * 数据量太大不适合二分查找\n    * 二分查找需要依赖数组，而数组为了支持随机访问的特性，要求内存空间是连续的，因此对内存的要求比较苛刻。比如，要存储1GB的数据，则需要1GB的连续内存空间。\n    * 这里的**连续**是指：即使有2GB内存空间剩余，但是这些空间是零散的，没有连续的1GB的空间，那照样无法申请一个1GB的数组。\n### 问题\n假设我们有 1000 万个整数数据，每个数据占 8 个字节，如何设计数据结构和算法，快速判断某个整数是否出现在这 1000 万数据中？ 我们希望这个功能不要占用太多的内存空间，最多不要超过 100MB，你会怎么做呢？\n  * 1000 * 10^4 * 8 / 10^6 = 80MB，可以使用数组存储80MB的整数，然后排序，使用二分查找取得某个数据。\n  * 大部分情况下，使用二分查找可以解决的问题，散列表和二叉树也可以解决，那么是否可以用散列表或者二叉树呢？答案是否定的。因为散列表和二叉树都需要额外的存储，100MB必然不够。\n\n\n\n## 排序\n\n| 排序算法 | 最好       | 最坏       | 平均       | 额外空间复杂度 | 稳定性 | 原地排序 |\n| -------- | ---------- | ---------- | ---------- | -------------- | ------ | :------: |\n| 冒泡排序   | O(n)   | O(n^2)  | O(n^2)   | O(1)         | 是     | 是       |\n| 插入排序   | O(n)    | O(n^2)   | O(n^2)   | O(1)         | 是     | 是       |\n| 选择排序   | O(n^2)   | O(n^2)   | O(n^2)   | O(1)         | 否     | 是       |\n| 归并排序   | O(nlogn) | O(nlogn) | O(nlogn) | O(n)         | 是     | 否       |\n| 快速排序   | O(nlogn) | O(n^2)   | O(nlogn) | O(1)         | 否     | 是       |\n| 堆排序 | O(nlogn) | O(nlogn) | O(nlogn) | O(1) | 否 | 是 |\n| 桶排序 | O(n) | - | - | O(n) | 是 | 否 |\n| 计数排序 | O(n+k)(k是数据范围) | - | - | O(k) | 是 | 否 |\n| 基数排序 | O(n*d)(d是维度) | - | - | O(n*d) | 是 | 否 |\n\n\n\n## 递归\n\n### 什么是递归？\n\n### 如何实现递归？\n\n### 递归存在的问题是什么？\n\n### 递归的应用\n\n\n\n\n## 设计思想\n\n### 空间换时间\n\n当内存空间较为充足的时候，如果需要追求代码的执行速度，那么我们就可以选择空间复杂度相对较高，时间复杂度相对较低的数据结构或者算法。\n\n### 时间换空间\n\n当内存比较紧缺的时候，例如代码执行在手机或单片机上的时候，那么我们就需要选择空间复杂度相对较低，空间复杂度相对较低的数据结构或者算法。\n\n事实上，我们不可能既保证时间的效率又保证空间的效率，我们只能尽力实现二者的平衡，根据实际权衡时间和空间。\n\n## 缓存\n\n**缓存**是一种提高数据读取性能的技术，在软件开发与硬件设计中应用非常广泛。\n\n\n\n### 缓存的设计思想\n\n缓存利用了**空间换时间**的设计思想。\n\n如果我们把数据存储在硬盘上，会比较节省内存，但是查找数据的时候，则需要从硬盘把数据读入，速度非常慢。通过缓存技术，事先将数据从硬盘加载到了内存中，这样查询数据的时候，就可以从内存中直接读取，因为内存中读取数据的速度远远快于硬盘中读取数据的速度，因此速度非常快，但是此时内存空间就变少了，相当于利用空间换时间。\n\n### 缓存的特征\n\n**命中率**：当某个请求通过访问缓存而得到响应时，缓存命中。缓存的命中率越高，则缓存的利用率也就越高。\n\n**最大空间**：缓存通常位于内存中，内存速度虽然要快于硬盘，但是内存的空间要远远小于硬盘，因此缓存的最大空间不可能非常大。\n\n**淘汰策略**：缓存的大小有限，当缓存存放的数据量大于最大空间时，就涉及到数据的淘汰问题。常见的缓存淘汰策略有：\n\n- 最少使用策略LFU(Least Frequently Used)：优先淘汰最少使用的数据。\n\n- 先进先出策略FIFO(First In, First Out)：在实时性要求的场景下，需要经常访问最新的数据，就可以使用FIFO，使得最先进入的数据被淘汰。\n\n- 最近最少使用策略LRU(Least Recently Used)：优先淘汰最久未使用的数据，也就是上次被访问时间距离现在最久的数据。LRU可以保证内存中的数据都是热点数据，即经常被访问的数据，从而保证缓存的命中率。\n\n\n\n\n\n\n\n\n"
  }
]