剑指 offer 题解.md 94.1 KB
Newer Older
C
CyC2018 已提交
1
<!-- GFM-TOC -->
C
CyC2018 已提交
2
* [1. 前言](#1-前言)
C
CyC2018 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
* [2. 实现 Singleton](#2-实现-singleton)
* [3. 数组中重复的数字](#3-数组中重复的数字)
* [4. 二维数组中的查找](#4-二维数组中的查找)
* [5. 替换空格](#5-替换空格)
* [6. 从尾到头打印链表](#6-从尾到头打印链表)
* [7. 重建二叉树](#7-重建二叉树)
* [8. 二叉树的下一个结点](#8-二叉树的下一个结点)
* [9. 用两个栈实现队列](#9-用两个栈实现队列)
* [10.1 斐波那契数列](#101-斐波那契数列)
* [10.2 跳台阶](#102-跳台阶)
* [10.3 变态跳台阶](#103-变态跳台阶)
* [10.4 矩形覆盖](#104-矩形覆盖)
* [11. 旋转数组的最小数字](#11-旋转数组的最小数字)
* [12. 矩阵中的路径](#12-矩阵中的路径)
* [13. 机器人的运动范围](#13-机器人的运动范围)
* [14. 剪绳子](#14-剪绳子)
* [15. 二进制中 1 的个数](#15-二进制中-1-的个数)
* [16. 数值的整数次方](#16-数值的整数次方)
* [17. 打印从 1 到最大的 n 位数](#17-打印从-1-到最大的-n-位数)
* [18.1 在 O(1) 时间内删除链表节点](#181-在-o1-时间内删除链表节点)
* [18.2 删除链表中重复的结点](#182-删除链表中重复的结点)
* [19. 正则表达式匹配](#19-正则表达式匹配)
* [20. 表示数值的字符串](#20-表示数值的字符串)
* [21. 调整数组顺序使奇数位于偶数前面](#21-调整数组顺序使奇数位于偶数前面)
* [22. 链表中倒数第 K 个结点](#22-链表中倒数第-k-个结点)
* [23. 链表中环的入口结点](#23-链表中环的入口结点)
* [24. 反转链表](#24-反转链表)
* [25. 合并两个排序的链表](#25-合并两个排序的链表)
* [26. 树的子结构](#26-树的子结构)
* [27. 二叉树的镜像](#27-二叉树的镜像)
* [28 对称的二叉树](#28-对称的二叉树)
* [29. 顺时针打印矩阵](#29-顺时针打印矩阵)
* [30. 包含 min 函数的栈](#30-包含-min-函数的栈)
* [31. 栈的压入、弹出序列](#31-栈的压入弹出序列)
* [32.1 从上往下打印二叉树](#321-从上往下打印二叉树)
* [32.2 把二叉树打印成多行](#322-把二叉树打印成多行)
* [32.3 按之字形顺序打印二叉树](#323-按之字形顺序打印二叉树)
* [33. 二叉搜索树的后序遍历序列](#33-二叉搜索树的后序遍历序列)
* [34. 二叉树中和为某一值的路径](#34-二叉树中和为某一值的路径)
* [35. 复杂链表的复制](#35-复杂链表的复制)
* [36. 二叉搜索树与双向链表](#36-二叉搜索树与双向链表)
* [37. 序列化二叉树](#37-序列化二叉树)
* [38. 字符串的排列](#38-字符串的排列)
* [39. 数组中出现次数超过一半的数字](#39-数组中出现次数超过一半的数字)
* [40. 最小的 K 个数](#40-最小的-k-个数)
* [41.1 数据流中的中位数](#411-数据流中的中位数)
* [41.2 字符流中第一个不重复的字符](#412-字符流中第一个不重复的字符)
* [42. 连续子数组的最大和](#42-连续子数组的最大和)
* [43. 从 1 到 n 整数中 1 出现的次数](#43-从-1-到-n-整数中-1-出现的次数)
* [44. 数字序列中的某一位数字](#44-数字序列中的某一位数字)
* [45. 把数组排成最小的数](#45-把数组排成最小的数)
* [46. 把数字翻译成字符串](#46-把数字翻译成字符串)
* [47. 礼物的最大价值](#47-礼物的最大价值)
* [48. 最长不含重复字符的子字符串](#48-最长不含重复字符的子字符串)
* [49. 丑数](#49-丑数)
* [50. 第一个只出现一次的字符位置](#50-第一个只出现一次的字符位置)
* [51. 数组中的逆序对](#51-数组中的逆序对)
* [52. 两个链表的第一个公共结点](#52-两个链表的第一个公共结点)
* [53 数字在排序数组中出现的次数](#53-数字在排序数组中出现的次数)
* [54. 二叉搜索树的第 K 个结点](#54-二叉搜索树的第-k-个结点)
* [55.1 二叉树的深度](#551-二叉树的深度)
* [55.2 平衡二叉树](#552-平衡二叉树)
* [56. 数组中只出现一次的数字](#56-数组中只出现一次的数字)
* [57.1 和为 S 的两个数字](#571-和为-s-的两个数字)
* [57.2 和为 S 的连续正数序列](#572-和为-s-的连续正数序列)
* [58.1 翻转单词顺序列](#581-翻转单词顺序列)
* [58.2 左旋转字符串](#582-左旋转字符串)
* [59. 滑动窗口的最大值](#59-滑动窗口的最大值)
* [60. n 个骰子的点数](#60-n-个骰子的点数)
* [61. 扑克牌顺子](#61-扑克牌顺子)
* [62. 圆圈中最后剩下的数](#62-圆圈中最后剩下的数)
* [63. 股票的最大利润](#63-股票的最大利润)
* [64. 求 1+2+3+...+n](#64-求-123n)
* [65. 不用加减乘除做加法](#65-不用加减乘除做加法)
* [66. 构建乘积数组](#66-构建乘积数组)
* [67. 把字符串转换成整数](#67-把字符串转换成整数)
* [68. 树中两个节点的最低公共祖先](#68-树中两个节点的最低公共祖先)
* [参考文献](#参考文献)
<!-- GFM-TOC -->


C
CyC2018 已提交
84 85 86 87 88 89 90
# 1. 前言

本文的绘图可通过以下途径免费获得并使用:

- [ProcessOn](https://www.processon.com/view/5a3e4c7be4b0909c1aa18b49)
- [DrawIO](https://drive.google.com/file/d/1nSSCpPUC05MFoeFuf_aeTtkm7dG5-bJ1/view?usp=sharing)

C
CyC2018 已提交
91
# 2. 实现 Singleton
C
CyC2018 已提交
92

C
CyC2018 已提交
93
[单例模式](https://github.com/CyC2018/Interview-Notebook/blob/master/notes/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F.md)
C
CyC2018 已提交
94

C
CyC2018 已提交
95
# 3. 数组中重复的数字
C
CyC2018 已提交
96

C
CyC2018 已提交
97 98
[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)

C
CyC2018 已提交
99
## 题目描述
C
CyC2018 已提交
100

C
CyC2018 已提交
101
在一个长度为 n 的数组里的所有数字都在 0 到 n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字是重复的,也不知道每个数字重复几次。请找出数组中任意一个重复的数字。
C
CyC2018 已提交
102

C
CyC2018 已提交
103 104 105 106 107 108 109
```html
Input:
{2, 3, 1, 0, 2, 5}

Output:
2
```
C
CyC2018 已提交
110

C
CyC2018 已提交
111
## 解题思路
C
CyC2018 已提交
112

C
CyC2018 已提交
113 114
要求复杂度为 O(N) + O(1),也就是时间复杂度 O(N),空间复杂度 O(1)。因此不能使用排序的方法,也不能使用额外的标记数组。牛客网讨论区这一题的首票答案使用 nums[i] + length 来将元素标记,这么做会有加法溢出问题。

C
CyC2018 已提交
115
这种数组元素在 [0, n-1] 范围内的问题,可以将值为 i 的元素放到第 i 个位置上。
C
CyC2018 已提交
116

C
CyC2018 已提交
117
以 (2, 3, 1, 0, 2, 5) 为例:
C
CyC2018 已提交
118

C
CyC2018 已提交
119
```text-html-basic
C
CyC2018 已提交
120 121 122 123 124 125 126 127
position-0 : (2,3,1,0,2,5) // 2 <-> 1
             (1,3,2,0,2,5) // 1 <-> 3
             (3,1,2,0,2,5) // 3 <-> 0
             (0,1,2,3,2,5) // already in position
position-1 : (0,1,2,3,2,5) // already in position
position-2 : (0,1,2,3,2,5) // already in position
position-3 : (0,1,2,3,2,5) // already in position
position-4 : (0,1,2,3,2,5) // nums[i] == nums[nums[i]], exit
C
CyC2018 已提交
128 129
```

C
CyC2018 已提交
130
遍历到位置 4 时,该位置上的数为 2,但是第 2 个位置上已经有一个 2 的值了,因此可以知道 2 重复。
C
CyC2018 已提交
131 132

```java
C
CyC2018 已提交
133 134 135 136 137 138 139 140 141 142 143 144 145
public boolean duplicate(int[] nums, int length, int[] duplication) {
    if (nums == null || length <= 0)
        return false;
    for (int i = 0; i < length; i++) {
        while (nums[i] != i) {
            if (nums[i] == nums[nums[i]]) {
                duplication[0] = nums[i];
                return true;
            }
            swap(nums, i, nums[i]);
        }
    }
    return false;
C
CyC2018 已提交
146 147
}

C
CyC2018 已提交
148 149
private void swap(int[] nums, int i, int j) {
    int t = nums[i]; nums[i] = nums[j]; nums[j] = t;
C
CyC2018 已提交
150 151 152
}
```

C
CyC2018 已提交
153
# 4. 二维数组中的查找
C
CyC2018 已提交
154

C
CyC2018 已提交
155 156
[NowCoder](https://www.nowcoder.com/practice/abc3fe2ce8e146608e868a70efebf62e?tpId=13&tqId=11154&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking)

C
CyC2018 已提交
157
## 题目描述
C
CyC2018 已提交
158 159 160 161

在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。

```html
C
CyC2018 已提交
162
Consider the following matrix:
C
CyC2018 已提交
163
[
C
CyC2018 已提交
164 165 166 167 168
  [1,   4,  7, 11, 15],
  [2,   5,  8, 12, 19],
  [3,   6,  9, 16, 22],
  [10, 13, 14, 17, 24],
  [18, 21, 23, 26, 30]
C
CyC2018 已提交
169 170
]

C
CyC2018 已提交
171 172
Given target = 5, return true.
Given target = 20, return false.
C
CyC2018 已提交
173 174
```

C
CyC2018 已提交
175
## 解题思路
C
CyC2018 已提交
176

C
CyC2018 已提交
177 178 179 180
从右上角开始查找。矩阵中的一个数,它左边的数都比它小,下边的数都比它大。因此,从右上角开始查找,就可以根据 target 和当前元素的大小关系来缩小查找区间。

当前元素的查找区间为左下角的所有元素,例如元素 12 的查找区间如下:

C
CyC2018 已提交
181
<div align="center"> <img src="../pics//f94389e9-55b1-4f49-9d37-00ed05900ae0.png" width="250"/> </div><br>
C
CyC2018 已提交
182

C
CyC2018 已提交
183
复杂度:O(M + N) + O(1)
C
CyC2018 已提交
184 185

```java
C
CyC2018 已提交
186 187 188 189 190 191 192 193 194 195 196 197 198 199
public boolean Find(int target, int[][] matrix) {
    if (matrix == null || matrix.length == 0 || matrix[0].length == 0)
        return false;
    int rows = matrix.length, cols = matrix[0].length;
    int r = 0, c = cols - 1; // 从右上角开始
    while (r <= rows - 1 && c >= 0) {
        if (target == matrix[r][c])
            return true;
        else if (target > matrix[r][c])
            r++;
        else 
            c--;
    }
    return false;
C
CyC2018 已提交
200 201 202
}
```

C
CyC2018 已提交
203
# 5. 替换空格
C
CyC2018 已提交
204

C
CyC2018 已提交
205 206
[NowCoder](https://www.nowcoder.com/practice/4060ac7e3e404ad1a894ef3e17650423?tpId=13&tqId=11155&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking)

C
CyC2018 已提交
207
## 题目描述
C
CyC2018 已提交
208

C
CyC2018 已提交
209
请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为 We Are Happy. 则经过替换之后的字符串为 We%20Are%20Happy。
C
CyC2018 已提交
210

C
CyC2018 已提交
211
## 解题思路
C
CyC2018 已提交
212 213 214

在字符串尾部填充任意字符,使得字符串的长度等于字符串替换之后的长度。因为一个空格要替换成三个字符(%20),因此当遍历到一个空格时,需要在尾部填充两个任意字符。

C
CyC2018 已提交
215
令 P1 指向字符串原来的末尾位置,P2 指向字符串现在的末尾位置。P1 和 P2从后向前遍历,当 P1 遍历到一个空格时,就需要令 P2 指向的位置依次填充 02%(注意是逆序的),否则就填充上 P1 指向字符的值。
C
CyC2018 已提交
216

C
CyC2018 已提交
217
从后向前遍是为了在改变 P2 所指向的内容时,不会影响到 P1 遍历原来字符串的内容。
C
CyC2018 已提交
218

C
CyC2018 已提交
219
复杂度:O(N) + O(1)
C
CyC2018 已提交
220 221

```java
C
CyC2018 已提交
222 223 224 225 226
public String replaceSpace(StringBuffer str) {
    int oldLen = str.length();
    for (int i = 0; i < oldLen; i++)
        if (str.charAt(i) == ' ')
            str.append("  ");
C
CyC2018 已提交
227

C
CyC2018 已提交
228 229 230 231 232 233 234 235 236 237 238 239
    int P1 = oldLen - 1, P2 = str.length() - 1;
    while (P1 >= 0 && P2 > P1) {
        char c = str.charAt(P1--);
        if (c == ' ') {
            str.setCharAt(P2--, '0');
            str.setCharAt(P2--, '2');
            str.setCharAt(P2--, '%');
        } else {
            str.setCharAt(P2--, c);
        }
    }
    return str.toString();
C
CyC2018 已提交
240 241 242
}
```

C
CyC2018 已提交
243
# 6. 从尾到头打印链表
C
CyC2018 已提交
244

C
CyC2018 已提交
245 246
[NowCoder](https://www.nowcoder.com/practice/d0267f7f55b3412ba93bd35cfa8e8035?tpId=13&tqId=11156&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking)

C
CyC2018 已提交
247
## 题目描述
C
CyC2018 已提交
248 249 250

输入链表的第一个节点,从尾到头反过来打印出每个结点的值。

C
CyC2018 已提交
251
<div align="center"> <img src="../pics//d99dc9e2-197c-4085-813d-7195da1c6762.png" width="300"/> </div><br>
C
CyC2018 已提交
252

C
CyC2018 已提交
253
## 解题思路
C
CyC2018 已提交
254

C
CyC2018 已提交
255
### 使用栈
C
CyC2018 已提交
256 257

```java
C
CyC2018 已提交
258 259 260 261 262 263 264 265 266 267
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
    Stack<Integer> stack = new Stack<>();
    while (listNode != null) {
        stack.add(listNode.val);
        listNode = listNode.next;
    }
    ArrayList<Integer> ret = new ArrayList<>();
    while (!stack.isEmpty())
        ret.add(stack.pop());
    return ret;
C
CyC2018 已提交
268 269 270
}
```

C
CyC2018 已提交
271
### 使用递归
C
CyC2018 已提交
272 273

```java
C
CyC2018 已提交
274 275 276 277 278 279 280
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
    ArrayList<Integer> ret = new ArrayList<>();
    if (listNode != null) {
        ret.addAll(printListFromTailToHead(listNode.next));
        ret.add(listNode.val);
    }
    return ret;
C
CyC2018 已提交
281 282 283
}
```

C
CyC2018 已提交
284
### 使用头插法
C
CyC2018 已提交
285 286 287

利用链表头插法为逆序的特点。

C
CyC2018 已提交
288 289 290 291
头结点和第一个节点的区别:

- 头结点是在头插法中使用的一个额外节点,这个节点不存储值;
- 第一个节点就是链表的第一个真正存储值的节点。
C
CyC2018 已提交
292 293

```java
C
CyC2018 已提交
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
    // 头插法构建逆序链表
    ListNode head = new ListNode(-1);
    while (listNode != null) {
        ListNode memo = listNode.next;
        listNode.next = head.next;
        head.next = listNode;
        listNode = memo;
    }
    // 构建 ArrayList
    ArrayList<Integer> ret = new ArrayList<>();
    head = head.next;
    while (head != null) {
        ret.add(head.val);
        head = head.next;
    }
    return ret;
C
CyC2018 已提交
311 312 313
}
```

C
CyC2018 已提交
314 315 316 317 318 319 320 321 322 323 324 325 326 327
### 使用 Collections.reverse()

```java
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
    ArrayList<Integer> ret = new ArrayList<>();
    while (listNode != null) {
        ret.add(listNode.val);
        listNode = listNode.next;
    }
    Collections.reverse(ret);
    return ret;
}
```

C
CyC2018 已提交
328
# 7. 重建二叉树
C
CyC2018 已提交
329

C
CyC2018 已提交
330 331
[NowCoder](https://www.nowcoder.com/practice/8a19cbe657394eeaac2f6ea9b0f6fcf6?tpId=13&tqId=11157&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking)

C
CyC2018 已提交
332
## 题目描述
C
CyC2018 已提交
333

C
CyC2018 已提交
334
根据二叉树的前序遍历和中序遍历的结果,重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
C
CyC2018 已提交
335 336

```html
C
CyC2018 已提交
337 338
preorder = [3,9,20,15,7]
inorder =  [9,3,15,20,7]
C
CyC2018 已提交
339 340
```

C
CyC2018 已提交
341
<div align="center"> <img src="../pics//8a4c6ad4-a816-47d1-b93f-7ca4f78ab67a.png" width="250"/> </div><br>
C
CyC2018 已提交
342

C
CyC2018 已提交
343
## 解题思路
C
CyC2018 已提交
344 345 346 347

前序遍历的第一个值为根节点的值,使用这个值将中序遍历结果分成两部分,左部分为树的左子树中序遍历结果,右部分为树的右子树中序遍历的结果。

```java
C
CyC2018 已提交
348 349
// 缓存中序遍历数组的每个值对应的索引
private Map<Integer, Integer> inOrderNumsIndexs = new HashMap<>();
C
CyC2018 已提交
350

C
CyC2018 已提交
351 352 353
public TreeNode reConstructBinaryTree(int[] pre, int[] in) {
    for (int i = 0; i < in.length; i++)
        inOrderNumsIndexs.put(in[i], i);
C
CyC2018 已提交
354
    return reConstructBinaryTree(pre, 0, pre.length - 1, 0, in.length - 1);
C
CyC2018 已提交
355 356
}

C
CyC2018 已提交
357
private TreeNode reConstructBinaryTree(int[] pre, int preL, int preR, int inL, int inR) {
C
CyC2018 已提交
358 359 360 361 362
    if (preL > preR)
        return null;
    TreeNode root = new TreeNode(pre[preL]);
    int inIndex = inOrderNumsIndexs.get(root.val);
    int leftTreeSize = inIndex - inL;
C
CyC2018 已提交
363 364
    root.left = reConstructBinaryTree(pre, preL + 1, preL + leftTreeSize, inL, inL + leftTreeSize - 1);
    root.right = reConstructBinaryTree(pre, preL + leftTreeSize + 1, preR, inL + leftTreeSize + 1, inR);
C
CyC2018 已提交
365
    return root;
C
CyC2018 已提交
366 367 368
}
```

C
CyC2018 已提交
369
# 8. 二叉树的下一个结点
C
CyC2018 已提交
370

C
CyC2018 已提交
371 372
[NowCoder](https://www.nowcoder.com/practice/9023a0c988684a53960365b889ceaf5e?tpId=13&tqId=11210&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking)

C
CyC2018 已提交
373
## 题目描述
C
CyC2018 已提交
374 375 376 377

给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。

```java
C
CyC2018 已提交
378 379 380 381 382
public class TreeLinkNode {
    int val;
    TreeLinkNode left = null;
    TreeLinkNode right = null;
    TreeLinkNode next = null;
C
CyC2018 已提交
383

C
CyC2018 已提交
384 385 386
    TreeLinkNode(int val) {
        this.val = val;
    }
C
CyC2018 已提交
387 388 389
}
```

C
CyC2018 已提交
390 391 392 393 394 395 396 397 398 399
## 解题思路

① 如果一个节点的右子树不为空,那么该节点的下一个节点是右子树的最左节点;

<div align="center"> <img src="../pics//cb0ed469-27ab-471b-a830-648b279103c8.png" width="250"/> </div><br>

② 否则,向上找第一个左链接指向的树包含该节点的祖先节点。

<div align="center"> <img src="../pics//e143f6da-d114-4ba4-8712-f65299047fa2.png" width="250"/> </div><br>

C
CyC2018 已提交
400
```java
C
CyC2018 已提交
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
public TreeLinkNode GetNext(TreeLinkNode pNode) {
    if (pNode.right != null) {
        TreeLinkNode node = pNode.right;
        while (node.left != null)
            node = node.left;
        return node;
    } else {
        while (pNode.next != null) {
            TreeLinkNode parent = pNode.next;
            if (parent.left == pNode)
                return parent;
            pNode = pNode.next;
        }
    }
    return null;
C
CyC2018 已提交
416 417 418
}
```

C
CyC2018 已提交
419
# 9. 用两个栈实现队列
C
CyC2018 已提交
420

C
CyC2018 已提交
421 422
[NowCoder](https://www.nowcoder.com/practice/54275ddae22f475981afa2244dd448c6?tpId=13&tqId=11158&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking)

C
CyC2018 已提交
423
## 题目描述
C
CyC2018 已提交
424

C
CyC2018 已提交
425
用两个栈来实现一个队列,完成队列的 Push 和 Pop 操作。
C
CyC2018 已提交
426

C
CyC2018 已提交
427
## 解题思路
C
CyC2018 已提交
428

C
CyC2018 已提交
429
in 栈用来处理入栈(push)操作,out 栈用来处理出栈(pop)操作。一个元素进入 in 栈之后,出栈的顺序被反转。当元素要出栈时,需要先进入 out 栈,此时元素出栈顺序再一次被反转,因此出栈顺序就和最开始入栈顺序是相同的,先进入的元素先退出,这就是队列的顺序。
C
CyC2018 已提交
430

C
CyC2018 已提交
431
<div align="center"> <img src="../pics//5acf7550-86c5-4c5b-b912-8ce70ef9c34e.png" width="400"/> </div><br>
C
CyC2018 已提交
432 433

```java
C
CyC2018 已提交
434 435
Stack<Integer> in = new Stack<Integer>();
Stack<Integer> out = new Stack<Integer>();
C
CyC2018 已提交
436

C
CyC2018 已提交
437 438
public void push(int node) {
    in.push(node);
C
CyC2018 已提交
439 440
}

C
CyC2018 已提交
441 442 443 444
public int pop() throws Exception {
    if (out.isEmpty())
        while (!in.isEmpty())
            out.push(in.pop());
C
CyC2018 已提交
445

C
CyC2018 已提交
446 447
    if (out.isEmpty())
        throw new Exception("queue is empty");
C
CyC2018 已提交
448

C
CyC2018 已提交
449
    return out.pop();
C
CyC2018 已提交
450 451 452
}
```

C
CyC2018 已提交
453
# 10.1 斐波那契数列
C
CyC2018 已提交
454

C
CyC2018 已提交
455 456
[NowCoder](https://www.nowcoder.com/practice/c6c7742f5ba7442aada113136ddea0c3?tpId=13&tqId=11160&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking)

C
CyC2018 已提交
457
## 题目描述
C
CyC2018 已提交
458

C
CyC2018 已提交
459
求菲波那契数列的第 n 项,n <= 39。
C
CyC2018 已提交
460

C
CyC2018 已提交
461
<div align="center"><img src="https://latex.codecogs.com/gif.latex?f(n)=\left\{\begin{array}{rcl}0&&{n=0}\\1&&{n=1}\\f(n-1)+f(n-2)&&{n>1}\end{array}\right."/></div> <br>
C
CyC2018 已提交
462

C
CyC2018 已提交
463
## 解题思路
C
CyC2018 已提交
464

C
CyC2018 已提交
465
如果使用递归求解,会重复计算一些子问题。例如,计算 f(10) 需要计算 f(9) 和 f(8),计算 f(9) 需要计算 f(8) 和 f(7),可以看到 f(8) 被重复计算了。
C
CyC2018 已提交
466

C
CyC2018 已提交
467
<div align="center"> <img src="../pics//faecea49-9974-40db-9821-c8636137df61.jpg" width="300"/> </div><br>
C
CyC2018 已提交
468

C
CyC2018 已提交
469
递归是将一个问题划分成多个子问题求解,动态规划也是如此,但是动态规划会把子问题的解缓存起来,从而避免重复求解子问题。
C
CyC2018 已提交
470

C
CyC2018 已提交
471
```java
C
CyC2018 已提交
472 473 474 475 476 477 478 479
public int Fibonacci(int n) {
    if (n <= 1)
        return n;
    int[] fib = new int[n + 1];
    fib[1] = 1;
    for (int i = 2; i <= n; i++)
        fib[i] = fib[i - 1] + fib[i - 2];
    return fib[n];
C
CyC2018 已提交
480 481 482
}
```

C
CyC2018 已提交
483
考虑到第 i 项只与第 i-1 和第 i-2 项有关,因此只需要存储前两项的值就能求解第 i 项,从而将空间复杂度由 O(N) 降低为 O(1)。
C
CyC2018 已提交
484 485

```java
C
CyC2018 已提交
486 487 488 489 490 491 492 493 494 495 496
public int Fibonacci(int n) {
    if (n <= 1)
        return n;
    int pre2 = 0, pre1 = 1;
    int fib = 0;
    for (int i = 2; i <= n; i++) {
        fib = pre2 + pre1;
        pre2 = pre1;
        pre1 = fib;
    }
    return fib;
C
CyC2018 已提交
497 498 499
}
```

C
CyC2018 已提交
500
由于待求解的 n 小于 40,因此可以将前 40 项的结果先进行计算,之后就能以 O(1) 时间复杂度得到第 n 项的值了。
C
CyC2018 已提交
501

C
CyC2018 已提交
502
```java
C
CyC2018 已提交
503 504
public class Solution {
    private int[] fib = new int[40];
C
CyC2018 已提交
505

C
CyC2018 已提交
506 507 508 509 510 511
    public Solution() {
        fib[1] = 1;
        fib[2] = 2;
        for (int i = 2; i < fib.length; i++)
            fib[i] = fib[i - 1] + fib[i - 2];
    }
C
CyC2018 已提交
512

C
CyC2018 已提交
513 514 515
    public int Fibonacci(int n) {
        return fib[n];
    }
C
CyC2018 已提交
516 517 518
}
```

C
CyC2018 已提交
519
# 10.2 跳台阶
C
CyC2018 已提交
520

C
CyC2018 已提交
521 522
[NowCoder](https://www.nowcoder.com/practice/8c82a5b80378478f9484d87d1c5f12a4?tpId=13&tqId=11161&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking)

C
CyC2018 已提交
523
## 题目描述
C
CyC2018 已提交
524

C
CyC2018 已提交
525
一只青蛙一次可以跳上 1 级台阶,也可以跳上 2 级。求该青蛙跳上一个 n 级的台阶总共有多少种跳法。
C
CyC2018 已提交
526

C
CyC2018 已提交
527
## 解题思路
C
CyC2018 已提交
528

C
CyC2018 已提交
529
复杂度:O(N) + O(N)
C
CyC2018 已提交
530

C
CyC2018 已提交
531
```java
C
CyC2018 已提交
532 533 534 535 536 537 538 539 540
public int JumpFloor(int n) {
    if (n == 1)
        return 1;
    int[] dp = new int[n];
    dp[0] = 1;
    dp[1] = 2;
    for (int i = 2; i < n; i++)
        dp[i] = dp[i - 1] + dp[i - 2];
    return dp[n - 1];
C
CyC2018 已提交
541 542 543
}
```

C
CyC2018 已提交
544
复杂度:O(N) + O(1)
C
CyC2018 已提交
545 546

```java
C
CyC2018 已提交
547
public int JumpFloor(int n) {
C
CyC2018 已提交
548
    if (n <= 2)
C
CyC2018 已提交
549
        return n;
C
CyC2018 已提交
550 551 552
    int pre2 = 1, pre1 = 2;
    int result = 1;
    for (int i = 2; i < n; i++) {
C
CyC2018 已提交
553 554 555 556 557
        result = pre2 + pre1;
        pre2 = pre1;
        pre1 = result;
    }
    return result;
C
CyC2018 已提交
558 559 560
}
```

C
CyC2018 已提交
561
# 10.3 变态跳台阶
C
CyC2018 已提交
562

C
CyC2018 已提交
563 564
[NowCoder](https://www.nowcoder.com/practice/22243d016f6b47f2a6928b4313c85387?tpId=13&tqId=11162&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking)

C
CyC2018 已提交
565
## 题目描述
C
CyC2018 已提交
566

C
CyC2018 已提交
567
一只青蛙一次可以跳上 1 级台阶,也可以跳上 2 级... 它也可以跳上 n 级。求该青蛙跳上一个 n 级的台阶总共有多少种跳法。
C
CyC2018 已提交
568

C
CyC2018 已提交
569
## 解题思路
C
CyC2018 已提交
570 571

```java
C
CyC2018 已提交
572 573 574 575 576 577 578
public int JumpFloorII(int target) {
    int[] dp = new int[target];
    Arrays.fill(dp, 1);
    for (int i = 1; i < target; i++)
        for (int j = 0; j < i; j++)
            dp[i] += dp[j];
    return dp[target - 1];
C
CyC2018 已提交
579 580 581
}
```

C
CyC2018 已提交
582
# 10.4 矩形覆盖
C
CyC2018 已提交
583

C
CyC2018 已提交
584 585
[NowCoder](https://www.nowcoder.com/practice/72a5a919508a4251859fb2cfb987a0e6?tpId=13&tqId=11163&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking)

C
CyC2018 已提交
586
## 题目描述
C
CyC2018 已提交
587

C
CyC2018 已提交
588
我们可以用 2\*1 的小矩形横着或者竖着去覆盖更大的矩形。请问用 n 个 2\*1 的小矩形无重叠地覆盖一个 2\*n 的大矩形,总共有多少种方法?
C
CyC2018 已提交
589

C
CyC2018 已提交
590
## 解题思路
C
CyC2018 已提交
591

C
CyC2018 已提交
592
复杂度:O(N) + O(N)
C
CyC2018 已提交
593

C
CyC2018 已提交
594
```java
C
CyC2018 已提交
595 596 597 598 599 600 601 602 603
public int RectCover(int n) {
    if (n <= 2)
        return n;
    int[] dp = new int[n];
    dp[0] = 1;
    dp[1] = 2;
    for (int i = 2; i < n; i++)
        dp[i] = dp[i - 1] + dp[i - 2];
    return dp[n - 1];
C
CyC2018 已提交
604 605 606
}
```

C
CyC2018 已提交
607
复杂度:O(N) + O(1)
C
CyC2018 已提交
608 609

```java
C
CyC2018 已提交
610 611 612 613 614 615 616 617 618 619 620
public int RectCover(int n) {
    if (n <= 2)
        return n;
    int pre2 = 1, pre1 = 2;
    int result = 0;
    for (int i = 3; i <= n; i++) {
        result = pre2 + pre1;
        pre2 = pre1;
        pre1 = result;
    }
    return result;
C
CyC2018 已提交
621 622 623
}
```

C
CyC2018 已提交
624
# 11. 旋转数组的最小数字
C
CyC2018 已提交
625

C
CyC2018 已提交
626 627
[NowCoder](https://www.nowcoder.com/practice/9f3231a991af4f55b95579b44b7a01ba?tpId=13&tqId=11159&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking)

C
CyC2018 已提交
628
## 题目描述
C
CyC2018 已提交
629

C
CyC2018 已提交
630 631 632
把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。输入一个非递减排序的数组的一个旋转,输出旋转数组的最小元素。

例如数组 {3, 4, 5, 1, 2} 为 {1, 2, 3, 4, 5} 的一个旋转,该数组的最小值为 1。NOTE:给出的所有元素都大于 0,若数组大小为 0,请返回 0。
C
CyC2018 已提交
633

C
CyC2018 已提交
634
## 解题思路
C
CyC2018 已提交
635

C
CyC2018 已提交
636 637
- 当 nums[m] <= nums[h] 的情况下,说明解在 [l, m] 之间,此时令 h = m;
- 否则解在 [m + 1, h] 之间,令 l = m + 1。
C
CyC2018 已提交
638

C
CyC2018 已提交
639
因为 h 的赋值表达式为 h = m,因此循环体的循环条件应该为 l < h,详细解释请见 [Leetcode 题解](https://github.com/CyC2018/Interview-Notebook/blob/master/notes/Leetcode%20%E9%A2%98%E8%A7%A3.md) 二分查找部分。
C
CyC2018 已提交
640

C
CyC2018 已提交
641
但是如果出现 nums[l] == nums[m] == nums[h],那么此时无法确定解在哪个区间,需要切换到顺序查找。
C
CyC2018 已提交
642

C
CyC2018 已提交
643
复杂度:O(logN) + O(1)
C
CyC2018 已提交
644 645

```java
C
CyC2018 已提交
646 647 648 649 650 651
public int minNumberInRotateArray(int[] nums) {
    if (nums.length == 0)
        return 0;
    int l = 0, h = nums.length - 1;
    while (l < h) {
        int m = l + (h - l) / 2;
C
CyC2018 已提交
652 653 654
        if (nums[l] == nums[m] && nums[m] == nums[h])
            return minNumber(nums, l, h);
        else if (nums[m] <= nums[h])
C
CyC2018 已提交
655 656 657 658 659
            h = m;
        else
            l = m + 1;
    }
    return nums[l];
C
CyC2018 已提交
660
}
C
CyC2018 已提交
661 662 663 664 665 666 667

private int minNumber(int[] nums, int l, int h) {
    for (int i = l; i < h; i++)
        if (nums[i] > nums[i + 1])
            return nums[i + 1];
    return nums[l];
}
C
CyC2018 已提交
668 669
```

C
CyC2018 已提交
670
# 12. 矩阵中的路径
C
CyC2018 已提交
671

C
CyC2018 已提交
672 673
[NowCoder](https://www.nowcoder.com/practice/c61c6999eecb4b8f88a98f66b273a3cc?tpId=13&tqId=11218&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking)

C
CyC2018 已提交
674
## 题目描述
C
CyC2018 已提交
675 676 677

请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。

C
CyC2018 已提交
678
例如下面的矩阵包含了一条 bfce 路径。
C
CyC2018 已提交
679

C
CyC2018 已提交
680
<div align="center"> <img src="../pics//e31abb94-9201-4e06-9902-61101b92f475.png" width="300"/> </div><br>
C
CyC2018 已提交
681

C
CyC2018 已提交
682
## 解题思路
C
CyC2018 已提交
683 684

```java
C
CyC2018 已提交
685 686 687
private final static int[][] next = {{0, -1}, {0, 1}, {-1, 0}, {1, 0}};
private int rows;
private int cols;
C
CyC2018 已提交
688

C
CyC2018 已提交
689 690 691 692 693 694 695 696 697 698 699 700
public boolean hasPath(char[] array, int rows, int cols, char[] str) {
    if (rows == 0 || cols == 0)
        return false;
    this.rows = rows;
    this.cols = cols;
    boolean[][] marked = new boolean[rows][cols];
    char[][] matrix = buildMatrix(array);
    for (int i = 0; i < rows; i++)
        for (int j = 0; j < cols; j++)
            if (backtracking(matrix, str, marked, 0, i, j))
                return true;
    return false;
C
CyC2018 已提交
701 702
}

C
CyC2018 已提交
703 704 705 706 707 708 709 710 711 712 713
private boolean backtracking(char[][] matrix, char[] str, boolean[][] marked, int pathLen, int r, int c) {
    if (pathLen == str.length)
        return true;
    if (r < 0 || r >= rows || c < 0 || c >= cols || matrix[r][c] != str[pathLen] || marked[r][c])
        return false;
    marked[r][c] = true;
    for (int[] n : next)
        if (backtracking(matrix, str, marked, pathLen + 1, r + n[0], c + n[1]))
            return true;
    marked[r][c] = false;
    return false;
C
CyC2018 已提交
714 715
}

C
CyC2018 已提交
716 717 718 719 720 721
private char[][] buildMatrix(char[] array) {
    char[][] matrix = new char[rows][cols];
    for (int i = 0, idx = 0; i < rows; i++)
        for (int j = 0; j < cols; j++)
            matrix[i][j] = array[idx++];
    return matrix;
C
CyC2018 已提交
722 723 724
}
```

C
CyC2018 已提交
725
# 13. 机器人的运动范围
C
CyC2018 已提交
726

C
CyC2018 已提交
727 728
[NowCoder](https://www.nowcoder.com/practice/6e5207314b5241fb83f2329e89fdecc8?tpId=13&tqId=11219&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking)

C
CyC2018 已提交
729
## 题目描述
C
CyC2018 已提交
730

C
CyC2018 已提交
731
地上有一个 m 行和 n 列的方格。一个机器人从坐标 (0, 0) 的格子开始移动,每一次只能向左右上下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于 k 的格子。例如,当 k 为 18 时,机器人能够进入方格(35, 37),因为 3+5+3+7=18。但是,它不能进入方格(35, 38),因为 3+5+3+8=19。请问该机器人能够达到多少个格子?
C
CyC2018 已提交
732

C
CyC2018 已提交
733
## 解题思路
C
CyC2018 已提交
734 735

```java
C
CyC2018 已提交
736 737 738 739 740 741
private static final int[][] next = {{0, -1}, {0, 1}, {-1, 0}, {1, 0}};
private int cnt = 0;
private int rows;
private int cols;
private int threshold;
private int[][] digitSum;
C
CyC2018 已提交
742

C
CyC2018 已提交
743 744 745 746 747 748 749 750
public int movingCount(int threshold, int rows, int cols) {
    this.rows = rows;
    this.cols = cols;
    this.threshold = threshold;
    initDigitSum();
    boolean[][] marked = new boolean[rows][cols];
    dfs(marked, 0, 0);
    return cnt;
C
CyC2018 已提交
751 752
}

C
CyC2018 已提交
753 754 755 756 757 758 759 760 761
private void dfs(boolean[][] marked, int r, int c) {
    if (r < 0 || r >= rows || c < 0 || c >= cols || marked[r][c])
        return;
    marked[r][c] = true;
    if (this.digitSum[r][c] > this.threshold)
        return;
    cnt++;
    for (int[] n : next)
        dfs(marked, r + n[0], c + n[1]);
C
CyC2018 已提交
762 763
}

C
CyC2018 已提交
764 765 766 767 768 769 770 771 772
private void initDigitSum() {
    int[] digitSumOne = new int[Math.max(rows, cols)];
    for (int i = 0; i < digitSumOne.length; i++) {
        int n = i;
        while (n > 0) {
            digitSumOne[i] += n % 10;
            n /= 10;
        }
    }
C
CyC2018 已提交
773
    this.digitSum = new int[rows][cols];
C
CyC2018 已提交
774 775
    for (int i = 0; i < this.rows; i++)
        for (int j = 0; j < this.cols; j++)
C
CyC2018 已提交
776
            this.digitSum[i][j] = digitSumOne[i] + digitSumOne[j];
C
CyC2018 已提交
777 778 779
}
```

C
CyC2018 已提交
780
# 14. 剪绳子
C
CyC2018 已提交
781

C
CyC2018 已提交
782 783
[Leetcode](https://leetcode.com/problems/integer-break/description/)

C
CyC2018 已提交
784
## 题目描述
C
CyC2018 已提交
785 786 787

把一根绳子剪成多段,并且使得每段的长度乘积最大。

C
CyC2018 已提交
788 789 790
```html
n = 2
return 1 (2 = 1 + 1)
C
CyC2018 已提交
791

C
CyC2018 已提交
792 793
n = 10
return 36 (10 = 3 + 3 + 4)
C
CyC2018 已提交
794 795
```

C
CyC2018 已提交
796 797 798
## 解题思路

### 贪心
C
CyC2018 已提交
799

C
CyC2018 已提交
800
尽可能多剪长度为 3 的绳子,并且不允许有长度为 1 的绳子出现,如果出现了,就从已经切好长度为 3 的绳子中拿出一段与长度为 1 的绳子重新组合,把它们切成两段长度为 2 的绳子。
C
CyC2018 已提交
801

C
CyC2018 已提交
802
证明:当 n >= 5 时,3(n - 3) - 2(n - 2) = n - 5 >= 0。因此把长度大于 5 的绳子切成两段,令其中一段长度为 3 可以使得两段的乘积最大。
C
CyC2018 已提交
803 804

```java
C
CyC2018 已提交
805 806 807 808 809 810 811 812 813 814 815 816
public int integerBreak(int n) {
    if (n < 2)
        return 0;
    if (n == 2)
        return 1;
    if (n == 3)
        return 2;
    int timesOf3 = n / 3;
    if (n - timesOf3 * 3 == 1)
        timesOf3--;
    int timesOf2 = (n - timesOf3 * 3) / 2;
    return (int) (Math.pow(3, timesOf3)) * (int) (Math.pow(2, timesOf2));
C
CyC2018 已提交
817 818 819
}
```

C
CyC2018 已提交
820 821 822 823 824 825 826 827 828 829 830 831 832
### 动态规划

```java
public int integerBreak(int n) {
    int[] dp = new int[n + 1];
    dp[1] = 1;
    for (int i = 2; i <= n; i++)
        for (int j = 1; j < i; j++)
            dp[i] = Math.max(dp[i], Math.max(j * (i - j), dp[j] * (i - j)));
    return dp[n];
}
```

C
CyC2018 已提交
833
# 15. 二进制中 1 的个数
C
CyC2018 已提交
834

C
CyC2018 已提交
835 836
[NowCoder](https://www.nowcoder.com/practice/8ee967e43c2c4ec193b040ea7fbb10b8?tpId=13&tqId=11164&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking)

C
CyC2018 已提交
837
## 题目描述
C
CyC2018 已提交
838

C
CyC2018 已提交
839
输入一个整数,输出该数二进制表示中 1 的个数。
C
CyC2018 已提交
840

C
CyC2018 已提交
841
### Integer.bitCount()
C
CyC2018 已提交
842 843

```java
C
CyC2018 已提交
844 845
public int NumberOf1(int n) {
    return Integer.bitCount(n);
C
CyC2018 已提交
846 847 848
}
```

C
CyC2018 已提交
849
### n&(n-1)
C
CyC2018 已提交
850

C
CyC2018 已提交
851
O(M) 时间复杂度解法,其中 M 表示 1 的个数。
C
CyC2018 已提交
852

C
CyC2018 已提交
853
该位运算是去除 n 的位级表示中最低的那一位。
C
CyC2018 已提交
854 855

```
C
CyC2018 已提交
856 857 858
n       : 10110100
n-1     : 10110011
n&(n-1) : 10110000
C
CyC2018 已提交
859 860 861
```

```java
C
CyC2018 已提交
862 863 864 865 866 867 868
public int NumberOf1(int n) {
    int cnt = 0;
    while (n != 0) {
        cnt++;
        n &= (n - 1);
    }
    return cnt;
C
CyC2018 已提交
869 870 871
}
```

C
CyC2018 已提交
872
# 16. 数值的整数次方
C
CyC2018 已提交
873

C
CyC2018 已提交
874 875
[NowCoder](https://www.nowcoder.com/practice/1a834e5e3e1a4b7ba251417554e07c00?tpId=13&tqId=11165&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking)

C
CyC2018 已提交
876
## 题目描述
C
CyC2018 已提交
877

C
CyC2018 已提交
878
给定一个 double 类型的浮点数 base 和 int 类型的整数 exponent。求 base 的 exponent 次方。
C
CyC2018 已提交
879

C
CyC2018 已提交
880
## 解题思路
C
CyC2018 已提交
881

C
CyC2018 已提交
882
下面的讨论中 x 代表 base,n 代表 exponent。
C
CyC2018 已提交
883

C
CyC2018 已提交
884
<div align="center"><img src="https://latex.codecogs.com/gif.latex?x^n=\left\{\begin{array}{rcl}(x*x)^{n/2}&&{n\%2=0}\\x*(x*x)^{n/2}&&{n\%2=1}\end{array}\right."/></div> <br>
C
CyC2018 已提交
885

C
CyC2018 已提交
886
因为 (x\*x)<sup>n/2</sup> 可以通过递归求解,并且每递归一次,n 都减小一半,因此整个算法的时间复杂度为 O(logN)。
C
CyC2018 已提交
887 888

```java
C
CyC2018 已提交
889 890 891 892 893 894 895 896 897 898 899 900 901 902
public double Power(double base, int exponent) {
    if (exponent == 0)
        return 1;
    if (exponent == 1)
        return base;
    boolean isNegative = false;
    if (exponent < 0) {
        exponent = -exponent;
        isNegative = true;
    }
    double pow = Power(base * base, exponent / 2);
    if (exponent % 2 != 0)
        pow = pow * base;
    return isNegative ? 1 / pow : pow;
C
CyC2018 已提交
903 904 905
}
```

C
CyC2018 已提交
906
# 17. 打印从 1 到最大的 n 位数
C
CyC2018 已提交
907

C
CyC2018 已提交
908
## 题目描述
C
CyC2018 已提交
909

C
CyC2018 已提交
910
输入数字 n,按顺序打印出从 1 到最大的 n 位十进制数。比如输入 3,则打印出 1、2、3 一直到最大的 3 位数即 999。
C
CyC2018 已提交
911

C
CyC2018 已提交
912
## 解题思路
C
CyC2018 已提交
913

C
CyC2018 已提交
914
由于 n 可能会非常大,因此不能直接用 int 表示数字,而是用 char 数组进行存储。
C
CyC2018 已提交
915 916 917 918

使用回溯法得到所有的数。

```java
C
CyC2018 已提交
919 920 921 922
public void print1ToMaxOfNDigits(int n) {
    if (n <= 0)
        return;
    char[] number = new char[n];
C
CyC2018 已提交
923
    print1ToMaxOfNDigits(number, 0);
C
CyC2018 已提交
924 925
}

C
CyC2018 已提交
926
private void print1ToMaxOfNDigits(char[] number, int digit) {
C
CyC2018 已提交
927
    if (digit == number.length) {
C
CyC2018 已提交
928 929 930 931
        printNumber(number);
        return;
    }
    for (int i = 0; i < 10; i++) {
C
CyC2018 已提交
932
        number[digit] = (char) (i + '0');
C
CyC2018 已提交
933 934
        print1ToMaxOfNDigits(number, digit + 1);
    }
C
CyC2018 已提交
935 936
}

C
CyC2018 已提交
937 938 939 940 941 942 943
private void printNumber(char[] number) {
    int index = 0;
    while (index < number.length && number[index] == '0')
        index++;
    while (index < number.length)
        System.out.print(number[index++]);
    System.out.println();
C
CyC2018 已提交
944 945 946
}
```

C
CyC2018 已提交
947
# 18.1 在 O(1) 时间内删除链表节点
C
CyC2018 已提交
948

C
CyC2018 已提交
949
## 解题思路
C
CyC2018 已提交
950

C
CyC2018 已提交
951
① 如果该节点不是尾节点,那么可以直接将下一个节点的值赋给该节点,然后令该节点指向下下个节点,再删除下一个节点,时间复杂度为 O(1)。
C
CyC2018 已提交
952

C
CyC2018 已提交
953
<div align="center"> <img src="../pics//27ff9548-edb6-4465-92c8-7e6386e0b185.png" width="600"/> </div><br>
C
CyC2018 已提交
954

C
CyC2018 已提交
955
② 否则,就需要先遍历链表,找到节点的前一个节点,然后让前一个节点指向 null,时间复杂度为 O(N)。
C
CyC2018 已提交
956

C
CyC2018 已提交
957
<div align="center"> <img src="../pics//280f7728-594f-4811-a03a-fa8d32c013da.png" width="600"/> </div><br>
C
CyC2018 已提交
958

C
CyC2018 已提交
959
综上,如果进行 N 次操作,那么大约需要操作节点的次数为 N-1+N=2N-1,其中 N-1 表示 N-1 个不是尾节点的每个节点以 O(1) 的时间复杂度操作节点的总次数,N 表示 1 个尾节点以 O(N) 的时间复杂度操作节点的总次数。(2N-1)/N \~ 2,因此该算法的平均时间复杂度为 O(1)。
C
CyC2018 已提交
960 961

```java
C
CyC2018 已提交
962 963 964 965 966 967 968 969 970 971 972 973 974 975 976
public ListNode deleteNode(ListNode head, ListNode tobeDelete) {
    if (head == null || head.next == null || tobeDelete == null)
        return null;
    if (tobeDelete.next != null) {
        // 要删除的节点不是尾节点
        ListNode next = tobeDelete.next;
        tobeDelete.val = next.val;
        tobeDelete.next = next.next;
    } else {
        ListNode cur = head;
        while (cur.next != tobeDelete)
            cur = cur.next;
        cur.next = null;
    }
    return head;
C
CyC2018 已提交
977 978 979
}
```

C
CyC2018 已提交
980
# 18.2 删除链表中重复的结点
C
CyC2018 已提交
981

C
CyC2018 已提交
982 983
[NowCoder](https://www.nowcoder.com/practice/fc533c45b73a41b0b44ccba763f866ef?tpId=13&tqId=11209&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking)

C
CyC2018 已提交
984
## 题目描述
C
CyC2018 已提交
985

C
CyC2018 已提交
986
<div align="center"> <img src="../pics//8433fbb2-c35c-45ef-831d-e3ca42aebd51.png" width="500"/> </div><br>
C
CyC2018 已提交
987

C
CyC2018 已提交
988
## 解题描述
C
CyC2018 已提交
989 990

```java
C
CyC2018 已提交
991 992 993 994 995 996 997 998 999 1000 1001 1002
public ListNode deleteDuplication(ListNode pHead) {
    if (pHead == null || pHead.next == null)
        return pHead;
    ListNode next = pHead.next;
    if (pHead.val == next.val) {
        while (next != null && pHead.val == next.val)
            next = next.next;
        return deleteDuplication(next);
    } else {
        pHead.next = deleteDuplication(pHead.next);
        return pHead;
    }
C
CyC2018 已提交
1003 1004 1005
}
```

C
CyC2018 已提交
1006
# 19. 正则表达式匹配
C
CyC2018 已提交
1007

C
CyC2018 已提交
1008 1009
[NowCoder](https://www.nowcoder.com/practice/45327ae22b7b413ea21df13ee7d6429c?tpId=13&tqId=11205&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking)

C
CyC2018 已提交
1010
## 题目描述
C
CyC2018 已提交
1011

C
CyC2018 已提交
1012 1013 1014
请实现一个函数用来匹配包括 '.' 和 '\*' 的正则表达式。模式中的字符 '.' 表示任意一个字符,而 '\*' 表示它前面的字符可以出现任意次(包含 0 次)。

在本题中,匹配是指字符串的所有字符匹配整个模式。例如,字符串 "aaa" 与模式 "a.a" 和 "ab\*ac\*a" 匹配,但是与 "aa.a" 和 "ab\*a" 均不匹配。
C
CyC2018 已提交
1015

C
CyC2018 已提交
1016
## 解题思路
C
CyC2018 已提交
1017

C
CyC2018 已提交
1018
应该注意到,'.' 是用来当做一个任意字符,而 '\*' 是用来重复前面的字符。这两个的作用不同,不能把 '.' 的作用和 '\*' 进行类比,从而把它当成重复前面字符一次。
C
CyC2018 已提交
1019 1020

```java
C
CyC2018 已提交
1021 1022 1023
public boolean match(char[] str, char[] pattern) {
    int m = str.length, n = pattern.length;
    boolean[][] dp = new boolean[m + 1][n + 1];
C
CyC2018 已提交
1024

C
CyC2018 已提交
1025 1026 1027 1028
    dp[0][0] = true;
    for (int i = 1; i <= n; i++)
        if (pattern[i - 1] == '*')
            dp[0][i] = dp[0][i - 2];
C
CyC2018 已提交
1029

C
CyC2018 已提交
1030 1031 1032 1033 1034
    for (int i = 1; i <= m; i++)
        for (int j = 1; j <= n; j++)
            if (str[i - 1] == pattern[j - 1] || pattern[j - 1] == '.')
                dp[i][j] = dp[i - 1][j - 1];
            else if (pattern[j - 1] == '*')
C
CyC2018 已提交
1035 1036 1037 1038 1039 1040 1041
                if (pattern[j - 2] == str[i - 1] || pattern[j - 2] == '.') {
                    dp[i][j] |= dp[i][j - 1]; // a* counts as single a
                    dp[i][j] |= dp[i - 1][j]; // a* counts as multiple a
                    dp[i][j] |= dp[i][j - 2]; // a* counts as empty
                } else
                    dp[i][j] = dp[i][j - 2];   // a* only counts as empty

C
CyC2018 已提交
1042
    return dp[m][n];
C
CyC2018 已提交
1043 1044 1045
}
```

C
CyC2018 已提交
1046
# 20. 表示数值的字符串
C
CyC2018 已提交
1047

C
CyC2018 已提交
1048 1049
[NowCoder](https://www.nowcoder.com/practice/6f8c901d091949a5837e24bb82a731f2?tpId=13&tqId=11206&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking)

C
CyC2018 已提交
1050
## 题目描述
C
CyC2018 已提交
1051

C
CyC2018 已提交
1052 1053 1054
请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。

例如,字符串 "+100","5e2","-123","3.1416" 和 "-1E-16" 都表示数值。但是 "12e","1a3.14","1.2.3","+-5" 和 "12e+4.3" 都不是。
C
CyC2018 已提交
1055

C
CyC2018 已提交
1056
## 解题思路
C
CyC2018 已提交
1057

C
CyC2018 已提交
1058 1059 1060 1061
使用正则表达式进行匹配。

```html
[]  : 字符集合
C
CyC2018 已提交
1062
()  : 分组
C
CyC2018 已提交
1063 1064 1065 1066 1067
?   : 重复 0 ~ 1
+   : 重复 1 ~ n
*   : 重复 0 ~ n
.   : 任意字符
\\. : 转义后的 .
C
CyC2018 已提交
1068
\\d : 数字
C
CyC2018 已提交
1069 1070
```

C
CyC2018 已提交
1071
```java
C
CyC2018 已提交
1072 1073 1074 1075
public boolean isNumeric(char[] str) {
    if (str == null)
        return false;
    return new String(str).matches("[+-]?\\d*(\\.\\d+)?([eE][+-]?\\d+)?");
C
CyC2018 已提交
1076 1077 1078
}
```

C
CyC2018 已提交
1079
# 21. 调整数组顺序使奇数位于偶数前面
C
CyC2018 已提交
1080

C
CyC2018 已提交
1081 1082
[NowCoder](https://www.nowcoder.com/practice/beb5aa231adc45b2a5dcc5b62c93f593?tpId=13&tqId=11166&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking)

C
CyC2018 已提交
1083
## 题目描述
C
CyC2018 已提交
1084

C
CyC2018 已提交
1085
需要保证奇数和奇数,偶数和偶数之间的相对位置不变,这和书本不太一样。
C
CyC2018 已提交
1086

C
CyC2018 已提交
1087
## 解题思路
C
CyC2018 已提交
1088 1089

```java
C
CyC2018 已提交
1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103
public void reOrderArray(int[] nums) {
    // 奇数个数
    int oddCnt = 0;
    for (int val : nums)
        if (val % 2 == 1)
            oddCnt++;
    int[] copy = nums.clone();
    int i = 0, j = oddCnt;
    for (int num : copy) {
        if (num % 2 == 1)
            nums[i++] = num;
        else
            nums[j++] = num;
    }
C
CyC2018 已提交
1104 1105 1106
}
```

C
CyC2018 已提交
1107
# 22. 链表中倒数第 K 个结点
C
CyC2018 已提交
1108

C
CyC2018 已提交
1109 1110
[NowCoder](https://www.nowcoder.com/practice/529d3ae5a407492994ad2a246518148a?tpId=13&tqId=11167&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking)

C
CyC2018 已提交
1111
## 解题思路
C
CyC2018 已提交
1112

C
CyC2018 已提交
1113
设链表的长度为 N。设两个指针 P1 和 P2,先让 P1 移动 K 个节点,则还有 N - K 个节点可以移动。此时让 P1 和 P2 同时移动,可以知道当 P1 移动到链表结尾时,P2 移动到 N - K 个节点处,该位置就是倒数第 K 个节点。
C
CyC2018 已提交
1114

C
CyC2018 已提交
1115
<div align="center"> <img src="../pics//ea2304ce-268b-4238-9486-4d8f8aea8ca4.png" width="500"/> </div><br>
C
CyC2018 已提交
1116 1117

```java
C
CyC2018 已提交
1118 1119
public ListNode FindKthToTail(ListNode head, int k)
{
C
CyC2018 已提交
1120 1121
    if (head == null)
        return null;
C
CyC2018 已提交
1122 1123 1124
    ListNode P1 = head;
    while (P1 != null && k-- > 0)
        P1 = P1.next;
C
CyC2018 已提交
1125 1126
    if (k > 0)
        return null;
C
CyC2018 已提交
1127 1128 1129 1130
    ListNode P2 = head;
    while (P1 != null) {
        P1 = P1.next;
        P2 = P2.next;
C
CyC2018 已提交
1131
    }
C
CyC2018 已提交
1132
    return P2;
C
CyC2018 已提交
1133 1134 1135
}
```

C
CyC2018 已提交
1136
# 23. 链表中环的入口结点
C
CyC2018 已提交
1137

C
CyC2018 已提交
1138 1139
[NowCoder](https://www.nowcoder.com/practice/253d2c59ec3e4bc68da16833f79a38e4?tpId=13&tqId=11208&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking)

C
CyC2018 已提交
1140 1141 1142 1143 1144 1145
## 题目描述

一个链表中包含环,请找出该链表的环的入口结点。

要求不能使用额外的空间。

C
CyC2018 已提交
1146
## 解题思路
C
CyC2018 已提交
1147

C
CyC2018 已提交
1148
使用双指针,一个指针 fast 每次移动两个节点,一个指针 slow 每次移动一个节点。因为存在环,所以两个指针必定相遇在环中的某个节点上。假设相遇点在下图的 z1 位置,此时 fast 移动的节点数为 x+2y+z,slow 为 x+y,由于 fast 速度比 slow 快一倍,因此 x+2y+z=2(x+y),得到 x=z。
C
CyC2018 已提交
1149

C
CyC2018 已提交
1150
在相遇点,slow 要到环的入口点还需要移动 z 个节点,如果让 fast 重新从头开始移动,并且速度变为每次移动一个节点,那么它到环入口点还需要移动 x 个节点。在上面已经推导出 x=z,因此 fast 和 slow 将在环入口点相遇。
C
CyC2018 已提交
1151

C
CyC2018 已提交
1152
<div align="center"> <img src="../pics//2858f8ad-aedb-45a5-a706-e98c96d690fa.jpg" width="600"/> </div><br>
C
CyC2018 已提交
1153 1154

```java
C
CyC2018 已提交
1155 1156
public ListNode EntryNodeOfLoop(ListNode pHead)
{
C
CyC2018 已提交
1157 1158 1159
    if (pHead == null || pHead.next == null)
        return null;
    ListNode slow = pHead, fast = pHead;
C
CyC2018 已提交
1160
    do {
C
CyC2018 已提交
1161 1162
        fast = fast.next.next;
        slow = slow.next;
C
CyC2018 已提交
1163
    } while (slow != fast);
C
CyC2018 已提交
1164 1165 1166 1167 1168 1169
    fast = pHead;
    while (slow != fast) {
        slow = slow.next;
        fast = fast.next;
    }
    return slow;
C
CyC2018 已提交
1170 1171 1172
}
```

C
CyC2018 已提交
1173
# 24. 反转链表
C
CyC2018 已提交
1174

C
CyC2018 已提交
1175 1176
[NowCoder](https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca?tpId=13&tqId=11168&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking)

C
CyC2018 已提交
1177
## 解题思路
C
CyC2018 已提交
1178

C
CyC2018 已提交
1179
### 递归
C
CyC2018 已提交
1180 1181

```java
C
CyC2018 已提交
1182 1183 1184 1185 1186 1187 1188 1189
public ListNode ReverseList(ListNode head) {
    if (head == null || head.next == null)
        return head;
    ListNode next = head.next;
    head.next = null;
    ListNode newHead = ReverseList(next);
    next.next = head;
    return newHead;
C
CyC2018 已提交
1190 1191 1192
}
```

C
CyC2018 已提交
1193
### 迭代
C
CyC2018 已提交
1194 1195

```java
C
CyC2018 已提交
1196 1197 1198 1199 1200 1201 1202 1203 1204
public ListNode ReverseList(ListNode head) {
    ListNode newList = new ListNode(-1);
    while (head != null) {
        ListNode next = head.next;
        head.next = newList.next;
        newList.next = head;
        head = next;
    }
    return newList.next;
C
CyC2018 已提交
1205 1206 1207
}
```

C
CyC2018 已提交
1208
# 25. 合并两个排序的链表
C
CyC2018 已提交
1209

C
CyC2018 已提交
1210 1211
[NowCoder](https://www.nowcoder.com/practice/d8b6b4358f774294a89de2a6ac4d9337?tpId=13&tqId=11169&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking)

C
CyC2018 已提交
1212
## 题目描述
C
CyC2018 已提交
1213

C
CyC2018 已提交
1214
<div align="center"> <img src="../pics//43f2cafa-3568-4a89-a895-4725666b94a6.png" width="500"/> </div><br>
C
CyC2018 已提交
1215

C
CyC2018 已提交
1216
## 解题思路
C
CyC2018 已提交
1217

C
CyC2018 已提交
1218
### 递归
C
CyC2018 已提交
1219 1220

```java
C
CyC2018 已提交
1221
public ListNode Merge(ListNode list1, ListNode list2) {
C
CyC2018 已提交
1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232
    if (list1 == null)
        return list2;
    if (list2 == null)
        return list1;
    if (list1.val <= list2.val) {
        list1.next = Merge(list1.next, list2);
        return list1;
    } else {
        list2.next = Merge(list1, list2.next);
        return list2;
    }
C
CyC2018 已提交
1233 1234 1235
}
```

C
CyC2018 已提交
1236
### 迭代
C
CyC2018 已提交
1237 1238

```java
C
CyC2018 已提交
1239
public ListNode Merge(ListNode list1, ListNode list2) {
C
CyC2018 已提交
1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256
    ListNode head = new ListNode(-1);
    ListNode cur = head;
    while (list1 != null && list2 != null) {
        if (list1.val <= list2.val) {
            cur.next = list1;
            list1 = list1.next;
        } else {
            cur.next = list2;
            list2 = list2.next;
        }
        cur = cur.next;
    }
    if (list1 != null)
        cur.next = list1;
    if (list2 != null)
        cur.next = list2;
    return head.next;
C
CyC2018 已提交
1257 1258 1259
}
```

C
CyC2018 已提交
1260
# 26. 树的子结构
C
CyC2018 已提交
1261

C
CyC2018 已提交
1262 1263
[NowCoder](https://www.nowcoder.com/practice/6e196c44c7004d15b1610b9afca8bd88?tpId=13&tqId=11170&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking)

C
CyC2018 已提交
1264
## 题目描述
C
CyC2018 已提交
1265

C
CyC2018 已提交
1266
<div align="center"> <img src="../pics//4583e24f-424b-4d50-8a14-2c38a1827d4a.png" width="500"/> </div><br>
C
CyC2018 已提交
1267

C
CyC2018 已提交
1268
## 解题思路
C
CyC2018 已提交
1269 1270

```java
C
CyC2018 已提交
1271
public boolean HasSubtree(TreeNode root1, TreeNode root2) {
C
CyC2018 已提交
1272 1273
    if (root1 == null || root2 == null)
        return false;
C
CyC2018 已提交
1274
    return isSubtreeWithRoot(root1, root2) || HasSubtree(root1.left, root2) || HasSubtree(root1.right, root2);
C
CyC2018 已提交
1275 1276
}

C
CyC2018 已提交
1277
private boolean isSubtreeWithRoot(TreeNode root1, TreeNode root2) {
C
CyC2018 已提交
1278 1279 1280 1281 1282 1283
    if (root2 == null)
        return true;
    if (root1 == null)
        return false;
    if (root1.val != root2.val)
        return false;
C
CyC2018 已提交
1284
    return isSubtreeWithRoot(root1.left, root2.left) && isSubtreeWithRoot(root1.right, root2.right);
C
CyC2018 已提交
1285 1286 1287
}
```

C
CyC2018 已提交
1288
# 27. 二叉树的镜像
C
CyC2018 已提交
1289

C
CyC2018 已提交
1290 1291
[NowCoder](https://www.nowcoder.com/practice/564f4c26aa584921bc75623e48ca3011?tpId=13&tqId=11171&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking)

C
CyC2018 已提交
1292
## 题目描述
C
CyC2018 已提交
1293

C
CyC2018 已提交
1294
<div align="center"> <img src="../pics//a2d13178-f1ef-4811-a240-1fe95b55b1eb.png" width="300"/> </div><br>
C
CyC2018 已提交
1295

C
CyC2018 已提交
1296
## 解题思路
C
CyC2018 已提交
1297

C
CyC2018 已提交
1298 1299
### 递归

C
CyC2018 已提交
1300
```java
C
CyC2018 已提交
1301
public void Mirror(TreeNode root) {
C
CyC2018 已提交
1302 1303 1304 1305 1306
    if (root == null)
        return;
    swap(root);
    Mirror(root.left);
    Mirror(root.right);
C
CyC2018 已提交
1307 1308
}

C
CyC2018 已提交
1309
private void swap(TreeNode root) {
C
CyC2018 已提交
1310 1311 1312
    TreeNode t = root.left;
    root.left = root.right;
    root.right = t;
C
CyC2018 已提交
1313 1314 1315
}
```

C
CyC2018 已提交
1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338
### 迭代

```java
public void Mirror(TreeNode root) {
    Stack<TreeNode> stack = new Stack<>();
    stack.push(root);
    while (!stack.isEmpty()) {
        TreeNode node = stack.pop();
        if (node == null)
            continue;
        swap(node);
        stack.push(node.left);
        stack.push(node.right);
    }
}

private void swap(TreeNode node) {
    TreeNode t = node.left;
    node.left = node.right;
    node.right = t;
}
```

C
CyC2018 已提交
1339
# 28 对称的二叉树
C
CyC2018 已提交
1340

C
CyC2018 已提交
1341 1342
[NowCder](https://www.nowcoder.com/practice/ff05d44dfdb04e1d83bdbdab320efbcb?tpId=13&tqId=11211&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking)

C
CyC2018 已提交
1343
## 题目描述
C
CyC2018 已提交
1344

C
CyC2018 已提交
1345
<div align="center"> <img src="../pics//f42443e0-208d-41ea-be44-c7fd97d2e3bf.png" width="300"/> </div><br>
C
CyC2018 已提交
1346

C
CyC2018 已提交
1347
## 解题思路
C
CyC2018 已提交
1348 1349

```java
C
CyC2018 已提交
1350
boolean isSymmetrical(TreeNode pRoot) {
C
CyC2018 已提交
1351 1352 1353
    if (pRoot == null)
        return true;
    return isSymmetrical(pRoot.left, pRoot.right);
C
CyC2018 已提交
1354 1355
}

C
CyC2018 已提交
1356
boolean isSymmetrical(TreeNode t1, TreeNode t2) {
C
CyC2018 已提交
1357 1358 1359 1360 1361 1362 1363
    if (t1 == null && t2 == null)
        return true;
    if (t1 == null || t2 == null)
        return false;
    if (t1.val != t2.val)
        return false;
    return isSymmetrical(t1.left, t2.right) && isSymmetrical(t1.right, t2.left);
C
CyC2018 已提交
1364 1365 1366
}
```

C
CyC2018 已提交
1367
# 29. 顺时针打印矩阵
C
CyC2018 已提交
1368

C
CyC2018 已提交
1369 1370
[NowCoder](https://www.nowcoder.com/practice/9b4c81a02cd34f76be2659fa0d54342a?tpId=13&tqId=11172&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking)

C
CyC2018 已提交
1371
## 题目描述
C
CyC2018 已提交
1372

C
CyC2018 已提交
1373
下图的矩阵顺时针打印结果为:1, 2, 3, 4, 8, 12, 16, 15, 14, 13, 9, 5, 6, 7, 11, 10
C
CyC2018 已提交
1374

C
CyC2018 已提交
1375
<div align="center"> <img src="../pics//6539b9a4-2b24-4d10-8c94-2eb5aba1e296.png" width="300"/> </div><br>
C
CyC2018 已提交
1376

C
CyC2018 已提交
1377
## 解题思路
C
CyC2018 已提交
1378 1379

```java
C
CyC2018 已提交
1380
public ArrayList<Integer> printMatrix(int[][] matrix) {
C
CyC2018 已提交
1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396
    ArrayList<Integer> ret = new ArrayList<>();
    int r1 = 0, r2 = matrix.length - 1, c1 = 0, c2 = matrix[0].length - 1;
    while (r1 <= r2 && c1 <= c2) {
        for (int i = c1; i <= c2; i++)
            ret.add(matrix[r1][i]);
        for (int i = r1 + 1; i <= r2; i++)
            ret.add(matrix[i][c2]);
        if (r1 != r2)
            for (int i = c2 - 1; i >= c1; i--)
                ret.add(matrix[r2][i]);
        if (c1 != c2)
            for (int i = r2 - 1; i > r1; i--)
                ret.add(matrix[i][c1]);
        r1++; r2--; c1++; c2--;
    }
    return ret;
C
CyC2018 已提交
1397 1398 1399
}
```

C
CyC2018 已提交
1400
# 30. 包含 min 函数的栈
C
CyC2018 已提交
1401

C
CyC2018 已提交
1402 1403
[NowCoder](https://www.nowcoder.com/practice/4c776177d2c04c2494f2555c9fcc1e49?tpId=13&tqId=11173&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking)

C
CyC2018 已提交
1404
## 题目描述
C
CyC2018 已提交
1405

C
CyC2018 已提交
1406
定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的 min 函数。
C
CyC2018 已提交
1407

C
CyC2018 已提交
1408
## 解题思路
C
CyC2018 已提交
1409 1410

```java
C
CyC2018 已提交
1411
private Stack<Integer> dataStack = new Stack<>();
C
CyC2018 已提交
1412
private Stack<Integer> minStack = new Stack<>();
C
CyC2018 已提交
1413

C
CyC2018 已提交
1414
public void push(int node) {
C
CyC2018 已提交
1415
    dataStack.push(node);
C
CyC2018 已提交
1416
    minStack.push(minStack.isEmpty() ? node : Math.min(minStack.peek(), node));
C
CyC2018 已提交
1417 1418
}

C
CyC2018 已提交
1419
public void pop() {
C
CyC2018 已提交
1420
    dataStack.pop();
C
CyC2018 已提交
1421
    minStack.pop();
C
CyC2018 已提交
1422 1423
}

C
CyC2018 已提交
1424
public int top() {
C
CyC2018 已提交
1425
    return dataStack.peek();
C
CyC2018 已提交
1426 1427
}

C
CyC2018 已提交
1428
public int min() {
C
CyC2018 已提交
1429
    return minStack.peek();
C
CyC2018 已提交
1430 1431 1432
}
```

C
CyC2018 已提交
1433
# 31. 栈的压入、弹出序列
C
CyC2018 已提交
1434

C
CyC2018 已提交
1435 1436
[NowCoder](https://www.nowcoder.com/practice/d77d11405cc7470d82554cb392585106?tpId=13&tqId=11174&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking)

C
CyC2018 已提交
1437
## 题目描述
C
CyC2018 已提交
1438

C
CyC2018 已提交
1439
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列 1,2,3,4,5 是某栈的压入顺序,序列 4,5,3,2,1 是该压栈序列对应的一个弹出序列,但 4,3,5,1,2 就不可能是该压栈序列的弹出序列。
C
CyC2018 已提交
1440

C
CyC2018 已提交
1441
## 解题思路
C
CyC2018 已提交
1442 1443 1444 1445

使用一个栈来模拟压入弹出操作。

```java
C
CyC2018 已提交
1446
public boolean IsPopOrder(int[] pushSequence, int[] popSequence) {
C
CyC2018 已提交
1447
    int n = pushSequence.length;
C
CyC2018 已提交
1448 1449
    Stack<Integer> stack = new Stack<>();
    for (int pushIndex = 0, popIndex = 0; pushIndex < n; pushIndex++) {
C
CyC2018 已提交
1450 1451
        stack.push(pushSequence[pushIndex]);
        while (popIndex < n && stack.peek() == popSequence[popIndex]) {
C
CyC2018 已提交
1452 1453 1454 1455 1456
            stack.pop();
            popIndex++;
        }
    }
    return stack.isEmpty();
C
CyC2018 已提交
1457 1458 1459
}
```

C
CyC2018 已提交
1460
# 32.1 从上往下打印二叉树
C
CyC2018 已提交
1461

C
CyC2018 已提交
1462 1463
[NowCoder](https://www.nowcoder.com/practice/7fe2212963db4790b57431d9ed259701?tpId=13&tqId=11175&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking)

C
CyC2018 已提交
1464
## 题目描述
C
CyC2018 已提交
1465 1466 1467 1468 1469

从上往下打印出二叉树的每个节点,同层节点从左至右打印。

例如,以下二叉树层次遍历的结果为:1,2,3,4,5,6,7

C
CyC2018 已提交
1470
<div align="center"> <img src="../pics//348bc2db-582e-4aca-9f88-38c40e9a0e69.png" width="250"/> </div><br>
C
CyC2018 已提交
1471

C
CyC2018 已提交
1472
## 解题思路
C
CyC2018 已提交
1473 1474 1475 1476 1477 1478

使用队列来进行层次遍历。

不需要使用两个队列分别存储当前层的节点和下一层的节点,因为在开始遍历一层的节点时,当前队列中的节点数就是当前层的节点数,只要控制遍历这么多节点数,就能保证这次遍历的都是当前层的节点。

```java
C
CyC2018 已提交
1479
public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
C
CyC2018 已提交
1480 1481 1482 1483 1484 1485 1486
    Queue<TreeNode> queue = new LinkedList<>();
    ArrayList<Integer> ret = new ArrayList<>();
    queue.add(root);
    while (!queue.isEmpty()) {
        int cnt = queue.size();
        while (cnt-- > 0) {
            TreeNode t = queue.poll();
C
CyC2018 已提交
1487 1488
            if (t == null)
                continue;
C
CyC2018 已提交
1489
            ret.add(t.val);
C
CyC2018 已提交
1490 1491
            queue.add(t.left);
            queue.add(t.right);
C
CyC2018 已提交
1492 1493 1494
        }
    }
    return ret;
C
CyC2018 已提交
1495 1496 1497
}
```

C
CyC2018 已提交
1498
# 32.2 把二叉树打印成多行
C
CyC2018 已提交
1499

C
CyC2018 已提交
1500 1501
[NowCoder](https://www.nowcoder.com/practice/445c44d982d04483b04a54f298796288?tpId=13&tqId=11213&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking)

C
CyC2018 已提交
1502
## 题目描述
C
CyC2018 已提交
1503 1504 1505

和上题几乎一样。

C
CyC2018 已提交
1506
## 解题思路
C
CyC2018 已提交
1507 1508

```java
C
CyC2018 已提交
1509
ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) {
C
CyC2018 已提交
1510 1511 1512 1513 1514 1515 1516 1517
    ArrayList<ArrayList<Integer>> ret = new ArrayList<>();
    Queue<TreeNode> queue = new LinkedList<>();
    queue.add(pRoot);
    while (!queue.isEmpty()) {
        ArrayList<Integer> list = new ArrayList<>();
        int cnt = queue.size();
        while (cnt-- > 0) {
            TreeNode node = queue.poll();
C
CyC2018 已提交
1518 1519
            if (node == null)
                continue;
C
CyC2018 已提交
1520
            list.add(node.val);
C
CyC2018 已提交
1521 1522
            queue.add(node.left);
            queue.add(node.right);
C
CyC2018 已提交
1523
        }
C
CyC2018 已提交
1524 1525
        if (list.size() != 0)
            ret.add(list);
C
CyC2018 已提交
1526 1527
    }
    return ret;
C
CyC2018 已提交
1528 1529 1530
}
```

C
CyC2018 已提交
1531
# 32.3 按之字形顺序打印二叉树
C
CyC2018 已提交
1532

C
CyC2018 已提交
1533 1534
[NowCoder](https://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0?tpId=13&tqId=11212&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking)

C
CyC2018 已提交
1535
## 题目描述
C
CyC2018 已提交
1536 1537 1538

请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。

C
CyC2018 已提交
1539 1540 1541
## 解题思路

```java
C
CyC2018 已提交
1542
public ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) {
C
CyC2018 已提交
1543 1544 1545 1546 1547 1548 1549 1550 1551
    ArrayList<ArrayList<Integer>> ret = new ArrayList<>();
    Queue<TreeNode> queue = new LinkedList<>();
    queue.add(pRoot);
    boolean reverse = false;
    while (!queue.isEmpty()) {
        ArrayList<Integer> list = new ArrayList<>();
        int cnt = queue.size();
        while (cnt-- > 0) {
            TreeNode node = queue.poll();
C
CyC2018 已提交
1552 1553
            if (node == null)
                continue;
C
CyC2018 已提交
1554
            list.add(node.val);
C
CyC2018 已提交
1555 1556
            queue.add(node.left);
            queue.add(node.right);
C
CyC2018 已提交
1557 1558 1559 1560
        }
        if (reverse)
            Collections.reverse(list);
        reverse = !reverse;
C
CyC2018 已提交
1561 1562
        if (list.size() != 0)
            ret.add(list);
C
CyC2018 已提交
1563 1564 1565 1566 1567 1568
    }
    return ret;
}
```

# 33. 二叉搜索树的后序遍历序列
C
CyC2018 已提交
1569

C
CyC2018 已提交
1570 1571
[NowCoder](https://www.nowcoder.com/practice/a861533d45854474ac791d90e447bafd?tpId=13&tqId=11176&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking)

C
CyC2018 已提交
1572
## 题目描述
C
CyC2018 已提交
1573

C
CyC2018 已提交
1574
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。假设输入的数组的任意两个数字都互不相同。
C
CyC2018 已提交
1575

C
CyC2018 已提交
1576
例如,下图是后序遍历序列 3,1,2 所对应的二叉搜索树。
C
CyC2018 已提交
1577

C
CyC2018 已提交
1578
<div align="center"> <img src="../pics//836a4eaf-4798-4e48-b52a-a3dab9435ace.png" width="150"/> </div><br>
C
CyC2018 已提交
1579

C
CyC2018 已提交
1580
## 解题思路
C
CyC2018 已提交
1581 1582

```java
C
CyC2018 已提交
1583
public boolean VerifySquenceOfBST(int[] sequence) {
C
CyC2018 已提交
1584 1585 1586
    if (sequence == null || sequence.length == 0)
        return false;
    return verify(sequence, 0, sequence.length - 1);
C
CyC2018 已提交
1587 1588
}

C
CyC2018 已提交
1589
private boolean verify(int[] sequence, int first, int last) {
C
CyC2018 已提交
1590 1591 1592 1593 1594 1595 1596 1597 1598 1599
    if (last - first <= 1)
        return true;
    int rootVal = sequence[last];
    int cutIndex = first;
    while (cutIndex < last && sequence[cutIndex] <= rootVal)
        cutIndex++;
    for (int i = cutIndex + 1; i < last; i++)
        if (sequence[i] < rootVal)
            return false;
    return verify(sequence, first, cutIndex - 1) && verify(sequence, cutIndex, last - 1);
C
CyC2018 已提交
1600 1601 1602
}
```

C
CyC2018 已提交
1603
# 34. 二叉树中和为某一值的路径
C
CyC2018 已提交
1604

C
CyC2018 已提交
1605 1606
[NowCoder](https://www.nowcoder.com/practice/b736e784e3e34731af99065031301bca?tpId=13&tqId=11177&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking)

C
CyC2018 已提交
1607
## 题目描述
C
CyC2018 已提交
1608 1609 1610

输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。

C
CyC2018 已提交
1611
下图的二叉树有两条和为 22 的路径:10, 5, 7 和 10, 12
C
CyC2018 已提交
1612

C
CyC2018 已提交
1613
<div align="center"> <img src="../pics//f5477abd-c246-4851-89ab-6b1cde2549b1.png" width="200"/> </div><br>
C
CyC2018 已提交
1614

C
CyC2018 已提交
1615
## 解题思路
C
CyC2018 已提交
1616 1617

```java
C
CyC2018 已提交
1618
private ArrayList<ArrayList<Integer>> ret = new ArrayList<>();
C
CyC2018 已提交
1619

C
CyC2018 已提交
1620
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root, int target) {
C
CyC2018 已提交
1621 1622
    backtracking(root, target, new ArrayList<>());
    return ret;
C
CyC2018 已提交
1623 1624
}

C
CyC2018 已提交
1625
private void backtracking(TreeNode node, int target, ArrayList<Integer> path) {
C
CyC2018 已提交
1626 1627 1628 1629 1630
    if (node == null)
        return;
    path.add(node.val);
    target -= node.val;
    if (target == 0 && node.left == null && node.right == null) {
C
CyC2018 已提交
1631
        ret.add(new ArrayList<>(path));
C
CyC2018 已提交
1632 1633 1634 1635 1636
    } else {
        backtracking(node.left, target, path);
        backtracking(node.right, target, path);
    }
    path.remove(path.size() - 1);
C
CyC2018 已提交
1637 1638 1639
}
```

C
CyC2018 已提交
1640
# 35. 复杂链表的复制
C
CyC2018 已提交
1641

C
CyC2018 已提交
1642 1643
[NowCoder](https://www.nowcoder.com/practice/f836b2c43afc4b35ad6adc41ec941dba?tpId=13&tqId=11178&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking)

C
CyC2018 已提交
1644
## 题目描述
C
CyC2018 已提交
1645

C
CyC2018 已提交
1646
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的 head。
C
CyC2018 已提交
1647

C
CyC2018 已提交
1648
```java
C
CyC2018 已提交
1649
public class RandomListNode {
C
CyC2018 已提交
1650 1651 1652 1653 1654 1655 1656 1657 1658 1659
    int label;
    RandomListNode next = null;
    RandomListNode random = null;

    RandomListNode(int label) {
        this.label = label;
    }
}
```

C
CyC2018 已提交
1660
<div align="center"> <img src="../pics//a01d1516-8168-461a-a24b-620b9cfc40f4.png" width="300"/> </div><br>
C
CyC2018 已提交
1661

C
CyC2018 已提交
1662
## 解题思路
C
CyC2018 已提交
1663 1664 1665

第一步,在每个节点的后面插入复制的节点。

C
CyC2018 已提交
1666
<div align="center"> <img src="../pics//2e6c72f5-3b8e-4e32-b87b-9491322628fe.png" width="600"/> </div><br>
C
CyC2018 已提交
1667

C
CyC2018 已提交
1668
第二步,对复制节点的 random 链接进行赋值。
C
CyC2018 已提交
1669

C
CyC2018 已提交
1670
<div align="center"> <img src="../pics//323ffd6c-8b54-4f3e-b361-555a6c8bf218.png" width="600"/> </div><br>
C
CyC2018 已提交
1671 1672 1673

第三步,拆分。

C
CyC2018 已提交
1674 1675 1676
<div align="center"> <img src="../pics//8f3b9519-d705-48fe-87ad-2e4052fc81d2.png" width="600"/> </div><br>

```java
C
CyC2018 已提交
1677
public RandomListNode Clone(RandomListNode pHead) {
C
CyC2018 已提交
1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708
    if (pHead == null)
        return null;
    // 插入新节点
    RandomListNode cur = pHead;
    while (cur != null) {
        RandomListNode clone = new RandomListNode(cur.label);
        clone.next = cur.next;
        cur.next = clone;
        cur = clone.next;
    }
    // 建立 random 链接
    cur = pHead;
    while (cur != null) {
        RandomListNode clone = cur.next;
        if (cur.random != null)
            clone.random = cur.random.next;
        cur = clone.next;
    }
    // 拆分
    cur = pHead;
    RandomListNode pCloneHead = pHead.next;
    while (cur.next != null) {
        RandomListNode next = cur.next;
        cur.next = next.next;
        cur = next;
    }
    return pCloneHead;
}
```

# 36. 二叉搜索树与双向链表
C
CyC2018 已提交
1709

C
CyC2018 已提交
1710 1711
[NowCoder](https://www.nowcoder.com/practice/947f6eb80d944a84850b0538bf0ec3a5?tpId=13&tqId=11179&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking)

C
CyC2018 已提交
1712
## 题目描述
C
CyC2018 已提交
1713 1714 1715

输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。

C
CyC2018 已提交
1716
<div align="center"> <img src="../pics//79b12431-6d9d-4a7d-985b-1b79bc5bf5fb.png" width="400"/> </div><br>
C
CyC2018 已提交
1717

C
CyC2018 已提交
1718
## 解题思路
C
CyC2018 已提交
1719 1720

```java
C
CyC2018 已提交
1721 1722
private TreeNode pre = null;
private TreeNode head = null;
C
CyC2018 已提交
1723

C
CyC2018 已提交
1724
public TreeNode Convert(TreeNode root) {
C
CyC2018 已提交
1725 1726
    inOrder(root);
    return head;
C
CyC2018 已提交
1727 1728
}

C
CyC2018 已提交
1729
private void inOrder(TreeNode node) {
C
CyC2018 已提交
1730 1731 1732 1733 1734 1735 1736 1737 1738 1739
    if (node == null)
        return;
    inOrder(node.left);
    node.left = pre;
    if (pre != null)
        pre.right = node;
    pre = node;
    if (head == null)
        head = node;
    inOrder(node.right);
C
CyC2018 已提交
1740 1741 1742
}
```

C
CyC2018 已提交
1743
# 37. 序列化二叉树
C
CyC2018 已提交
1744

C
CyC2018 已提交
1745 1746
[NowCoder](https://www.nowcoder.com/practice/cf7e25aa97c04cc1a68c8f040e71fb84?tpId=13&tqId=11214&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking)

C
CyC2018 已提交
1747
## 题目描述
C
CyC2018 已提交
1748 1749 1750

请实现两个函数,分别用来序列化和反序列化二叉树。

C
CyC2018 已提交
1751
## 解题思路
C
CyC2018 已提交
1752 1753

```java
C
CyC2018 已提交
1754
private String deserializeStr;
C
CyC2018 已提交
1755

C
CyC2018 已提交
1756
public String Serialize(TreeNode root) {
C
CyC2018 已提交
1757 1758 1759 1760
    if (root == null)
        return "#";
    return root.val + " " + Serialize(root.left) + " " + Serialize(root.right);
}
C
CyC2018 已提交
1761

C
CyC2018 已提交
1762
public TreeNode Deserialize(String str) {
C
CyC2018 已提交
1763 1764 1765
    deserializeStr = str;
    return Deserialize();
}
C
CyC2018 已提交
1766

C
CyC2018 已提交
1767
private TreeNode Deserialize() {
C
CyC2018 已提交
1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779
    if (deserializeStr.length() == 0)
        return null;
    int index = deserializeStr.indexOf(" ");
    String node = index == -1 ? deserializeStr : deserializeStr.substring(0, index);
    deserializeStr = index == -1 ? "" : deserializeStr.substring(index + 1);
    if (node.equals("#"))
        return null;
    int val = Integer.valueOf(node);
    TreeNode t = new TreeNode(val);
    t.left = Deserialize();
    t.right = Deserialize();
    return t;
C
CyC2018 已提交
1780 1781 1782
}
```

C
CyC2018 已提交
1783
# 38. 字符串的排列
C
CyC2018 已提交
1784

C
CyC2018 已提交
1785 1786
[NowCoder](https://www.nowcoder.com/practice/fe6b651b66ae47d7acce78ffdd9a96c7?tpId=13&tqId=11180&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking)

C
CyC2018 已提交
1787
## 题目描述
C
CyC2018 已提交
1788

C
CyC2018 已提交
1789
输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串 abc,则打印出由字符 a, b, c 所能排列出来的所有字符串 abc, acb, bac, bca, cab 和 cba。
C
CyC2018 已提交
1790

C
CyC2018 已提交
1791
## 解题思路
C
CyC2018 已提交
1792 1793

```java
C
CyC2018 已提交
1794
private ArrayList<String> ret = new ArrayList<>();
C
CyC2018 已提交
1795

C
CyC2018 已提交
1796
public ArrayList<String> Permutation(String str) {
C
CyC2018 已提交
1797 1798 1799 1800
    if (str.length() == 0)
        return ret;
    char[] chars = str.toCharArray();
    Arrays.sort(chars);
C
CyC2018 已提交
1801
    backtracking(chars, new boolean[chars.length], new StringBuilder());
C
CyC2018 已提交
1802
    return ret;
C
CyC2018 已提交
1803 1804
}

C
CyC2018 已提交
1805
private void backtracking(char[] chars, boolean[] hasUsed, StringBuilder s) {
C
CyC2018 已提交
1806 1807 1808 1809 1810 1811 1812
    if (s.length() == chars.length) {
        ret.add(s.toString());
        return;
    }
    for (int i = 0; i < chars.length; i++) {
        if (hasUsed[i])
            continue;
C
CyC2018 已提交
1813
        if (i != 0 && chars[i] == chars[i - 1] && !hasUsed[i - 1]) /* 保证不重复 */
C
CyC2018 已提交
1814 1815 1816 1817 1818 1819 1820
            continue;
        hasUsed[i] = true;
        s.append(chars[i]);
        backtracking(chars, hasUsed, s);
        s.deleteCharAt(s.length() - 1);
        hasUsed[i] = false;
    }
C
CyC2018 已提交
1821 1822 1823
}
```

C
CyC2018 已提交
1824
# 39. 数组中出现次数超过一半的数字
C
CyC2018 已提交
1825

C
CyC2018 已提交
1826 1827
[NowCoder](https://www.nowcoder.com/practice/e8a1b01a2df14cb2b228b30ee6a92163?tpId=13&tqId=11181&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking)

C
CyC2018 已提交
1828
## 解题思路
C
CyC2018 已提交
1829

C
CyC2018 已提交
1830
多数投票问题,可以利用 Boyer-Moore Majority Vote Algorithm 来解决这个问题,使得时间复杂度为 O(N)。
C
CyC2018 已提交
1831

C
CyC2018 已提交
1832
使用 cnt 来统计一个元素出现的次数,当遍历到的元素和统计元素不相等时,令 cnt--。如果前面查找了 i 个元素,且 cnt == 0,说明前 i 个元素没有 majority,或者有 majority,但是出现的次数少于 i / 2 ,因为如果多于 i / 2 的话 cnt 就一定不会为 0 。此时剩下的 n - i 个元素中,majority 的数目依然多于 (n - i) / 2,因此继续查找就能找出 majority。
C
CyC2018 已提交
1833 1834

```java
C
CyC2018 已提交
1835
public int MoreThanHalfNum_Solution(int[] nums) {
C
CyC2018 已提交
1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848
    int majority = nums[0];
    for (int i = 1, cnt = 1; i < nums.length; i++) {
        cnt = nums[i] == majority ? cnt + 1 : cnt - 1;
        if (cnt == 0) {
            majority = nums[i];
            cnt = 1;
        }
    }
    int cnt = 0;
    for (int val : nums)
        if (val == majority)
            cnt++;
    return cnt > nums.length / 2 ? majority : 0;
C
CyC2018 已提交
1849 1850 1851
}
```

C
CyC2018 已提交
1852
# 40. 最小的 K 个数
C
CyC2018 已提交
1853

C
CyC2018 已提交
1854 1855
[NowCoder](https://www.nowcoder.com/practice/6a296eb82cf844ca8539b57c23e6e9bf?tpId=13&tqId=11182&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking)

C
CyC2018 已提交
1856
## 解题思路
C
CyC2018 已提交
1857

C
CyC2018 已提交
1858
### 快速选择
C
CyC2018 已提交
1859

C
CyC2018 已提交
1860 1861
- 复杂度:O(N) + O(1)
- 只有当允许修改数组元素时才可以使用
C
CyC2018 已提交
1862

C
CyC2018 已提交
1863
快速排序的 partition() 方法,会返回一个整数 j 使得 a[l..j-1] 小于等于 a[j],且 a[j+1..h] 大于等于 a[j],此时 a[j] 就是数组的第 j 大元素。可以利用这个特性找出数组的第 K 个元素,这种找第 K 个元素的算法称为快速选择算法。
C
CyC2018 已提交
1864 1865

```java
C
CyC2018 已提交
1866
public ArrayList<Integer> GetLeastNumbers_Solution(int[] nums, int k) {
C
CyC2018 已提交
1867 1868 1869
    ArrayList<Integer> ret = new ArrayList<>();
    if (k > nums.length || k <= 0)
        return ret;
C
CyC2018 已提交
1870 1871
    findKthSmallest(nums, k - 1);
    /* findKthSmallest 会改变数组,使得前 k 个数都是最小的 k 个数 */
C
CyC2018 已提交
1872 1873 1874
    for (int i = 0; i < k; i++)
        ret.add(nums[i]);
    return ret;
C
CyC2018 已提交
1875
}
C
CyC2018 已提交
1876

C
CyC2018 已提交
1877
public void findKthSmallest(int[] nums, int k) {
C
CyC2018 已提交
1878 1879 1880 1881 1882 1883 1884 1885 1886 1887
    int l = 0, h = nums.length - 1;
    while (l < h) {
        int j = partition(nums, l, h);
        if (j == k)
            break;
        if (j > k)
            h = j - 1;
        else
            l = j + 1;
    }
C
CyC2018 已提交
1888
}
C
CyC2018 已提交
1889

C
CyC2018 已提交
1890
private int partition(int[] nums, int l, int h) {
C
CyC2018 已提交
1891
    int p = nums[l];     /* 切分元素 */
C
CyC2018 已提交
1892 1893
    int i = l, j = h + 1;
    while (true) {
C
CyC2018 已提交
1894 1895
        while (i != h && nums[++i] < p) ;
        while (j != l && nums[--j] > p) ;
C
CyC2018 已提交
1896 1897 1898 1899 1900 1901
        if (i >= j)
            break;
        swap(nums, i, j);
    }
    swap(nums, l, j);
    return j;
C
CyC2018 已提交
1902
}
C
CyC2018 已提交
1903

C
CyC2018 已提交
1904
private void swap(int[] nums, int i, int j) {
C
CyC2018 已提交
1905 1906 1907
    int t = nums[i];
    nums[i] = nums[j];
    nums[j] = t;
C
CyC2018 已提交
1908
}
C
CyC2018 已提交
1909 1910
```

C
CyC2018 已提交
1911
### 大小为 K 的最小堆
C
CyC2018 已提交
1912

C
CyC2018 已提交
1913 1914
- 复杂度:O(NlogK) + O(K)
- 特别适合处理海量数据
C
CyC2018 已提交
1915 1916 1917

应该使用大顶堆来维护最小堆,而不能直接创建一个小顶堆并设置一个大小,企图让小顶堆中的元素都是最小元素。

C
CyC2018 已提交
1918
维护一个大小为 K 的最小堆过程如下:在添加一个元素之后,如果大顶堆的大小大于 K,那么需要将大顶堆的堆顶元素去除。
C
CyC2018 已提交
1919 1920

```java
C
CyC2018 已提交
1921
public ArrayList<Integer> GetLeastNumbers_Solution(int[] nums, int k) {
C
CyC2018 已提交
1922 1923 1924 1925 1926 1927 1928 1929
    if (k > nums.length || k <= 0)
        return new ArrayList<>();
    PriorityQueue<Integer> maxHeap = new PriorityQueue<>((o1, o2) -> o2 - o1);
    for (int num : nums) {
        maxHeap.add(num);
        if (maxHeap.size() > k)
            maxHeap.poll();
    }
C
CyC2018 已提交
1930
    return new ArrayList<>(maxHeap);
C
CyC2018 已提交
1931 1932 1933
}
```

C
CyC2018 已提交
1934
# 41.1 数据流中的中位数
C
CyC2018 已提交
1935

C
CyC2018 已提交
1936 1937
[NowCoder](https://www.nowcoder.com/practice/9be0172896bd43948f8a32fb954e1be1?tpId=13&tqId=11216&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking)

C
CyC2018 已提交
1938
## 题目描述
C
CyC2018 已提交
1939 1940 1941

如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值。如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。

C
CyC2018 已提交
1942
## 解题思路
C
CyC2018 已提交
1943 1944

```java
C
CyC2018 已提交
1945 1946 1947 1948 1949 1950 1951
/* 大顶堆,存储左半边元素 */
private PriorityQueue<Integer> left = new PriorityQueue<>((o1, o2) -> o2 - o1);
/* 小顶堆,存储右半边元素,并且右半边元素都大于左半边 */
private PriorityQueue<Integer> right = new PriorityQueue<>();
/* 当前数据流读入的元素个数 */
private int N = 0;

C
CyC2018 已提交
1952
public void Insert(Integer val) {
C
CyC2018 已提交
1953 1954 1955 1956 1957 1958 1959 1960 1961 1962
    /* 插入要保证两个堆存于平衡状态 */
    if (N % 2 == 0) {
        /* N 为偶数的情况下插入到右半边。
         * 因为右半边元素都要大于左半边,但是新插入的元素不一定比左半边元素来的大,
         * 因此需要先将元素插入左半边,然后利用左半边为大顶堆的特点,取出堆顶元素即为最大元素,此时插入右半边 */
        left.add(val);
        right.add(left.poll());
    } else {
        right.add(val);
        left.add(right.poll());
C
CyC2018 已提交
1963
    }
C
CyC2018 已提交
1964 1965
    N++;
}
C
CyC2018 已提交
1966

C
CyC2018 已提交
1967
public Double GetMedian() {
C
CyC2018 已提交
1968 1969 1970 1971
    if (N % 2 == 0)
        return (left.peek() + right.peek()) / 2.0;
    else
        return (double) right.peek();
C
CyC2018 已提交
1972 1973 1974
}
```

C
CyC2018 已提交
1975
# 41.2 字符流中第一个不重复的字符
C
CyC2018 已提交
1976

C
CyC2018 已提交
1977 1978
[NowCoder](https://www.nowcoder.com/practice/00de97733b8e4f97a3fb5c680ee10720?tpId=13&tqId=11207&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking)

C
CyC2018 已提交
1979
## 题目描述
C
CyC2018 已提交
1980

C
CyC2018 已提交
1981
请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符 "go" 时,第一个只出现一次的字符是 "g"。当从该字符流中读出前六个字符“google" 时,第一个只出现一次的字符是 "l"。
C
CyC2018 已提交
1982

C
CyC2018 已提交
1983
## 解题思路
C
CyC2018 已提交
1984 1985

```java
C
CyC2018 已提交
1986 1987
private int[] cnts = new int[256];
private Queue<Character> queue = new LinkedList<>();
C
CyC2018 已提交
1988

C
CyC2018 已提交
1989
public void Insert(char ch) {
C
CyC2018 已提交
1990 1991 1992 1993
    cnts[ch]++;
    queue.add(ch);
    while (!queue.isEmpty() && cnts[queue.peek()] > 1)
        queue.poll();
C
CyC2018 已提交
1994
}
C
CyC2018 已提交
1995

C
CyC2018 已提交
1996
public char FirstAppearingOnce() {
C
CyC2018 已提交
1997
    return queue.isEmpty() ? '#' : queue.peek();
C
CyC2018 已提交
1998 1999 2000
}
```

C
CyC2018 已提交
2001
# 42. 连续子数组的最大和
C
CyC2018 已提交
2002

C
CyC2018 已提交
2003 2004
[NowCoder](https://www.nowcoder.com/practice/459bd355da1549fa8a49e350bf3df484?tpId=13&tqId=11183&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking)

C
CyC2018 已提交
2005
## 题目描述
C
CyC2018 已提交
2006

C
CyC2018 已提交
2007
{6, -3, -2, 7, -15, 1, 2, 2},连续子数组的最大和为 8(从第 0 个开始,到第 3 个为止)。
C
CyC2018 已提交
2008

C
CyC2018 已提交
2009
## 解题思路
C
CyC2018 已提交
2010 2011

```java
C
CyC2018 已提交
2012
public int FindGreatestSumOfSubArray(int[] nums) {
C
CyC2018 已提交
2013 2014
    if (nums == null || nums.length == 0)
        return 0;
C
CyC2018 已提交
2015
    int greatestSum = Integer.MIN_VALUE;
C
CyC2018 已提交
2016 2017 2018
    int sum = 0;
    for (int val : nums) {
        sum = sum <= 0 ? val : sum + val;
C
CyC2018 已提交
2019
        greatestSum = Math.max(greatestSum, sum);
C
CyC2018 已提交
2020
    }
C
CyC2018 已提交
2021
    return greatestSum;
C
CyC2018 已提交
2022
}
C
CyC2018 已提交
2023 2024
```

C
CyC2018 已提交
2025
# 43. 从 1 到 n 整数中 1 出现的次数
C
CyC2018 已提交
2026

C
CyC2018 已提交
2027
[NowCoder](https://www.nowcoder.com/practice/bd7f978302044eee894445e244c7eee6?tpId=13&tqId=11184&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking)
C
CyC2018 已提交
2028

C
CyC2018 已提交
2029
## 解题思路
C
CyC2018 已提交
2030 2031

```java
C
CyC2018 已提交
2032
public int NumberOf1Between1AndN_Solution(int n) {
C
CyC2018 已提交
2033 2034 2035 2036 2037 2038
    int cnt = 0;
    for (int m = 1; m <= n; m *= 10) {
        int a = n / m, b = n % m;
        cnt += (a + 8) / 10 * m + (a % 10 == 1 ? b + 1 : 0);
    }
    return cnt;
C
CyC2018 已提交
2039 2040 2041
}
```

C
CyC2018 已提交
2042
> [Leetcode : 233. Number of Digit One](https://leetcode.com/problems/number-of-digit-one/discuss/64381/4+-lines-O(log-n)-C++JavaPython)
C
CyC2018 已提交
2043

C
CyC2018 已提交
2044
# 44. 数字序列中的某一位数字
C
CyC2018 已提交
2045

C
CyC2018 已提交
2046
## 题目描述
C
CyC2018 已提交
2047

C
CyC2018 已提交
2048
数字以 0123456789101112131415... 的格式序列化到一个字符串中,求这个字符串的第 index 位。
C
CyC2018 已提交
2049

C
CyC2018 已提交
2050
## 解题思路
C
CyC2018 已提交
2051 2052

```java
C
CyC2018 已提交
2053
public int getDigitAtIndex(int index) {
C
CyC2018 已提交
2054 2055
    if (index < 0)
        return -1;
C
CyC2018 已提交
2056
    int place = 1;  // 1 表示个位,2 表示 十位...
C
CyC2018 已提交
2057
    while (true) {
C
CyC2018 已提交
2058 2059
        int amount = getAmountOfPlace(place);
        int totalAmount = amount * place;
C
CyC2018 已提交
2060
        if (index < totalAmount)
C
CyC2018 已提交
2061
            return getDigitAtIndex(index, place);
C
CyC2018 已提交
2062
        index -= totalAmount;
C
CyC2018 已提交
2063
        place++;
C
CyC2018 已提交
2064
    }
C
CyC2018 已提交
2065 2066 2067
}

/**
C
CyC2018 已提交
2068 2069
 * place 位数的数字组成的字符串长度
 * 10, 90, 900, ...
C
CyC2018 已提交
2070
 */
C
CyC2018 已提交
2071
private int getAmountOfPlace(int place) {
C
CyC2018 已提交
2072
    if (place == 1)
C
CyC2018 已提交
2073
        return 10;
C
CyC2018 已提交
2074
    return (int) Math.pow(10, place - 1) * 9;
C
CyC2018 已提交
2075 2076 2077
}

/**
C
CyC2018 已提交
2078 2079
 * place 位数的起始数字
 * 0, 10, 100, ...
C
CyC2018 已提交
2080
 */
C
CyC2018 已提交
2081
private int getBeginNumberOfPlace(int place) {
C
CyC2018 已提交
2082 2083 2084
    if (place == 1)
        return 0;
    return (int) Math.pow(10, place - 1);
C
CyC2018 已提交
2085 2086 2087
}

/**
C
CyC2018 已提交
2088
 * 在 place 位数组成的字符串中,第 index 个数
C
CyC2018 已提交
2089
 */
C
CyC2018 已提交
2090
private int getDigitAtIndex(int index, int place) {
C
CyC2018 已提交
2091 2092 2093 2094 2095
    int beginNumber = getBeginNumberOfPlace(place);
    int shiftNumber = index / place;
    String number = (beginNumber + shiftNumber) + "";
    int count = index % place;
    return number.charAt(count) - '0';
C
CyC2018 已提交
2096 2097 2098
}
```

C
CyC2018 已提交
2099
# 45. 把数组排成最小的数
C
CyC2018 已提交
2100

C
CyC2018 已提交
2101 2102
[NowCoder](https://www.nowcoder.com/practice/8fecd3f8ba334add803bf2a06af1b993?tpId=13&tqId=11185&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking)

C
CyC2018 已提交
2103
## 题目描述
C
CyC2018 已提交
2104

C
CyC2018 已提交
2105
输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组 {3,32,321},则打印出这三个数字能排成的最小数字为 321323。
C
CyC2018 已提交
2106

C
CyC2018 已提交
2107
## 解题思路
C
CyC2018 已提交
2108

C
CyC2018 已提交
2109
可以看成是一个排序问题,在比较两个字符串 S1 和 S2 的大小时,应该比较的是 S1+S2 和 S2+S1 的大小,如果 S1+S2 < S2+S1,那么应该把 S1 排在前面,否则应该把 S2 排在前面。
C
CyC2018 已提交
2110 2111

```java
C
CyC2018 已提交
2112
public String PrintMinNumber(int[] numbers) {
C
CyC2018 已提交
2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123
    if (numbers == null || numbers.length == 0)
        return "";
    int n = numbers.length;
    String[] nums = new String[n];
    for (int i = 0; i < n; i++)
        nums[i] = numbers[i] + "";
    Arrays.sort(nums, (s1, s2) -> (s1 + s2).compareTo(s2 + s1));
    String ret = "";
    for (String str : nums)
        ret += str;
    return ret;
C
CyC2018 已提交
2124 2125 2126
}
```

C
CyC2018 已提交
2127
# 46. 把数字翻译成字符串
C
CyC2018 已提交
2128

C
CyC2018 已提交
2129 2130
[Leetcode](https://leetcode.com/problems/decode-ways/description/)

C
CyC2018 已提交
2131
## 题目描述
C
CyC2018 已提交
2132

C
CyC2018 已提交
2133
给定一个数字,按照如下规则翻译成字符串:0 翻译成“a”,1 翻译成“b”... 25 翻译成“z”。一个数字有多种翻译可能,例如 12258 一共有 5 种,分别是 bccfi,bwfi,bczi,mcfi,mzi。实现一个函数,用来计算一个数字有多少种不同的翻译方法。
C
CyC2018 已提交
2134

C
CyC2018 已提交
2135
## 解题思路
C
CyC2018 已提交
2136 2137

```java
C
CyC2018 已提交
2138
public int numDecodings(String s) {
C
CyC2018 已提交
2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155
    if (s == null || s.length() == 0)
        return 0;
    int n = s.length();
    int[] dp = new int[n + 1];
    dp[0] = 1;
    dp[1] = s.charAt(0) == '0' ? 0 : 1;
    for (int i = 2; i <= n; i++) {
        int one = Integer.valueOf(s.substring(i - 1, i));
        if (one != 0)
            dp[i] += dp[i - 1];
        if (s.charAt(i - 2) == '0')
            continue;
        int two = Integer.valueOf(s.substring(i - 2, i));
        if (two <= 26)
            dp[i] += dp[i - 2];
    }
    return dp[n];
C
CyC2018 已提交
2156 2157 2158
}
```

C
CyC2018 已提交
2159
# 47. 礼物的最大价值
C
CyC2018 已提交
2160

C
CyC2018 已提交
2161 2162
[NowCoder](https://www.nowcoder.com/questionTerminal/72a99e28381a407991f2c96d8cb238ab)

C
CyC2018 已提交
2163
## 题目描述
C
CyC2018 已提交
2164

C
CyC2018 已提交
2165
在一个 m\*n 的棋盘的每一个格都放有一个礼物,每个礼物都有一定价值(大于 0)。从左上角开始拿礼物,每次向右或向下移动一格,直到右下角结束。给定一个棋盘,求拿到礼物的最大价值。例如,对于如下棋盘
C
CyC2018 已提交
2166 2167

```
C
CyC2018 已提交
2168 2169 2170 2171
1    10   3    8
12   2    9    6
5    7    4    11
3    7    16   5
C
CyC2018 已提交
2172 2173
```

C
CyC2018 已提交
2174
礼物的最大价值为 1+12+5+7+7+16+5=53。
C
CyC2018 已提交
2175

C
CyC2018 已提交
2176
## 解题思路
C
CyC2018 已提交
2177 2178 2179 2180

应该用动态规划求解,而不是深度优先搜索,深度优先搜索过于复杂,不是最优解。

```java
C
CyC2018 已提交
2181
public int getMost(int[][] values) {
C
CyC2018 已提交
2182 2183
    if (values == null || values.length == 0 || values[0].length == 0)
        return 0;
C
CyC2018 已提交
2184
    int n = values[0].length;
C
CyC2018 已提交
2185
    int[] dp = new int[n];
C
CyC2018 已提交
2186 2187 2188 2189
    for (int[] value : values) {
        dp[0] += value[0];
        for (int i = 1; i < n; i++)
            dp[i] = Math.max(dp[i], dp[i - 1]) + value[i];
C
CyC2018 已提交
2190 2191
    }
    return dp[n - 1];
C
CyC2018 已提交
2192 2193 2194
}
```

C
CyC2018 已提交
2195
# 48. 最长不含重复字符的子字符串
C
CyC2018 已提交
2196

C
CyC2018 已提交
2197
## 题目描述
C
CyC2018 已提交
2198

C
CyC2018 已提交
2199
输入一个字符串(只包含 a\~z 的字符),求其最长不含重复字符的子字符串的长度。例如对于 arabcacfr,最长不含重复字符的子字符串为 acfr,长度为 4。
C
CyC2018 已提交
2200

C
CyC2018 已提交
2201
## 解题思路
C
CyC2018 已提交
2202 2203

```java
C
CyC2018 已提交
2204
public int longestSubStringWithoutDuplication(String str) {
C
CyC2018 已提交
2205 2206 2207 2208
    int curLen = 0;
    int maxLen = 0;
    int[] preIndexs = new int[26];
    Arrays.fill(preIndexs, -1);
C
CyC2018 已提交
2209 2210 2211 2212
    for (int curI = 0; curI < str.length(); curI++) {
        int c = str.charAt(curI) - 'a';
        int preI = preIndexs[c];
        if (preI == -1 || curI - preI > curLen) {
C
CyC2018 已提交
2213 2214 2215
            curLen++;
        } else {
            maxLen = Math.max(maxLen, curLen);
C
CyC2018 已提交
2216
            curLen = curI - preI;
C
CyC2018 已提交
2217
        }
C
CyC2018 已提交
2218
        preIndexs[c] = curI;
C
CyC2018 已提交
2219 2220 2221
    }
    maxLen = Math.max(maxLen, curLen);
    return maxLen;
C
CyC2018 已提交
2222 2223 2224
}
```

C
CyC2018 已提交
2225
# 49. 丑数
C
CyC2018 已提交
2226

C
CyC2018 已提交
2227 2228
[NowCoder](https://www.nowcoder.com/practice/6aa9e04fc3794f68acf8778237ba065b?tpId=13&tqId=11186&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking)

C
CyC2018 已提交
2229
## 题目描述
C
CyC2018 已提交
2230

C
CyC2018 已提交
2231
把只包含因子 2、3 和 5 的数称作丑数(Ugly Number)。例如 6、8 都是丑数,但 14 不是,因为它包含因子 7。习惯上我们把 1 当做是第一个丑数。求按从小到大的顺序的第 N 个丑数。
C
CyC2018 已提交
2232

C
CyC2018 已提交
2233
## 解题思路
C
CyC2018 已提交
2234 2235

```java
C
CyC2018 已提交
2236
public int GetUglyNumber_Solution(int N) {
C
CyC2018 已提交
2237 2238
    if (N <= 6)
        return N;
C
CyC2018 已提交
2239
    int i2 = 0, i3 = 0, i5 = 0;
C
CyC2018 已提交
2240
    int[] dp = new int[N];
C
CyC2018 已提交
2241
    dp[0] = 1;
C
CyC2018 已提交
2242 2243 2244 2245
    for (int i = 1; i < N; i++) {
        int next2 = dp[i2] * 2, next3 = dp[i3] * 3, next5 = dp[i5] * 5;
        dp[i] = Math.min(next2, Math.min(next3, next5));
        if (dp[i] == next2)
C
CyC2018 已提交
2246
            i2++;
C
CyC2018 已提交
2247
        if (dp[i] == next3)
C
CyC2018 已提交
2248
            i3++;
C
CyC2018 已提交
2249
        if (dp[i] == next5)
C
CyC2018 已提交
2250 2251
            i5++;
    }
C
CyC2018 已提交
2252
    return dp[N - 1];
C
CyC2018 已提交
2253 2254 2255
}
```

C
CyC2018 已提交
2256
# 50. 第一个只出现一次的字符位置
C
CyC2018 已提交
2257

C
CyC2018 已提交
2258 2259
[NowCoder](https://www.nowcoder.com/practice/1c82e8cf713b4bbeb2a5b31cf5b0417c?tpId=13&tqId=11187&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking)

C
CyC2018 已提交
2260
## 题目描述
C
CyC2018 已提交
2261

C
CyC2018 已提交
2262
在一个字符串 (1 <= 字符串长度 <= 10000,全部由字母组成) 中找到第一个只出现一次的字符,并返回它的位置。
C
CyC2018 已提交
2263

C
CyC2018 已提交
2264
## 解题思路
C
CyC2018 已提交
2265

C
CyC2018 已提交
2266
最直观的解法是使用 HashMap 对出现次数进行统计,但是考虑到要统计的字符范围有限,因此可以使用整型数组代替 HashMap。
C
CyC2018 已提交
2267 2268

```java
C
CyC2018 已提交
2269
public int FirstNotRepeatingChar(String str) {
C
CyC2018 已提交
2270 2271 2272 2273 2274 2275 2276
    int[] cnts = new int[256];
    for (int i = 0; i < str.length(); i++)
        cnts[str.charAt(i)]++;
    for (int i = 0; i < str.length(); i++)
        if (cnts[str.charAt(i)] == 1)
            return i;
    return -1;
C
CyC2018 已提交
2277 2278 2279
}
```

C
CyC2018 已提交
2280
以上实现的空间复杂度还不是最优的。考虑到只需要找到只出现一次的字符,那么我们只需要统计的次数信息只有 0,1,更大,使用两个比特位就能存储这些信息。
C
CyC2018 已提交
2281 2282

```java
C
CyC2018 已提交
2283
public int FirstNotRepeatingChar2(String str) {
C
CyC2018 已提交
2284 2285 2286 2287
    BitSet bs1 = new BitSet(256);
    BitSet bs2 = new BitSet(256);
    for (char c : str.toCharArray()) {
        if (!bs1.get(c) && !bs2.get(c))
C
CyC2018 已提交
2288
            bs1.set(c);     // 0 0 -> 0 1
C
CyC2018 已提交
2289
        else if (bs1.get(c) && !bs2.get(c))
C
CyC2018 已提交
2290
            bs2.set(c);     // 0 1 -> 1 1
C
CyC2018 已提交
2291 2292 2293
    }
    for (int i = 0; i < str.length(); i++) {
        char c = str.charAt(i);
C
CyC2018 已提交
2294
        if (bs1.get(c) && !bs2.get(c))  // 0 1
C
CyC2018 已提交
2295 2296 2297
            return i;
    }
    return -1;
C
CyC2018 已提交
2298 2299 2300
}
```

C
CyC2018 已提交
2301
# 51. 数组中的逆序对
C
CyC2018 已提交
2302

C
CyC2018 已提交
2303 2304
[NowCoder](https://www.nowcoder.com/practice/96bd6684e04a44eb80e6a68efc0ec6c5?tpId=13&tqId=11188&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking)

C
CyC2018 已提交
2305
## 题目描述
C
CyC2018 已提交
2306

C
CyC2018 已提交
2307
在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数 P。
C
CyC2018 已提交
2308

C
CyC2018 已提交
2309
## 解题思路
C
CyC2018 已提交
2310 2311

```java
C
CyC2018 已提交
2312
private long cnt = 0;
C
CyC2018 已提交
2313
private int[] tmp;  // 在这里创建辅助数组,而不是在 merge() 递归函数中创建
C
CyC2018 已提交
2314

C
CyC2018 已提交
2315
public int InversePairs(int[] nums) {
C
CyC2018 已提交
2316 2317 2318
    tmp = new int[nums.length];
    mergeSort(nums, 0, nums.length - 1);
    return (int) (cnt % 1000000007);
C
CyC2018 已提交
2319 2320
}

C
CyC2018 已提交
2321
private void mergeSort(int[] nums, int l, int h) {
C
CyC2018 已提交
2322 2323 2324 2325 2326 2327
    if (h - l < 1)
        return;
    int m = l + (h - l) / 2;
    mergeSort(nums, l, m);
    mergeSort(nums, m + 1, h);
    merge(nums, l, m, h);
C
CyC2018 已提交
2328 2329
}

C
CyC2018 已提交
2330
private void merge(int[] nums, int l, int m, int h) {
C
CyC2018 已提交
2331 2332 2333 2334 2335 2336 2337 2338 2339 2340
    int i = l, j = m + 1, k = l;
    while (i <= m || j <= h) {
        if (i > m)
            tmp[k] = nums[j++];
        else if (j > h)
            tmp[k] = nums[i++];
        else if (nums[i] < nums[j])
            tmp[k] = nums[i++];
        else {
            tmp[k] = nums[j++];
C
CyC2018 已提交
2341
            this.cnt += m - i + 1;  // nums[i] >= nums[j],说明 nums[i...mid] 都大于 nums[j]
C
CyC2018 已提交
2342 2343 2344 2345 2346
        }
        k++;
    }
    for (k = l; k <= h; k++)
        nums[k] = tmp[k];
C
CyC2018 已提交
2347 2348 2349
}
```

C
CyC2018 已提交
2350
# 52. 两个链表的第一个公共结点
C
CyC2018 已提交
2351

C
CyC2018 已提交
2352 2353
[NowCoder](https://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46?tpId=13&tqId=11189&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking)

C
CyC2018 已提交
2354
## 题目描述
C
CyC2018 已提交
2355

C
CyC2018 已提交
2356
<div align="center"> <img src="../pics//8f6f9dc9-9ecd-47c8-b50e-2814f0219056.png" width="500"/> </div><br>
C
CyC2018 已提交
2357

C
CyC2018 已提交
2358
## 解题思路
C
CyC2018 已提交
2359

C
CyC2018 已提交
2360
设 A 的长度为 a + c,B 的长度为 b + c,其中 c 为尾部公共部分长度,可知 a + c + b = b + c + a。
C
CyC2018 已提交
2361

C
CyC2018 已提交
2362
当访问 A 链表的指针访问到链表尾部时,令它从链表 B 的头部重新开始访问链表 B;同样地,当访问 B 链表的指针访问到链表尾部时,令它从链表 A 的头部重新开始访问链表 A。这样就能控制访问 A 和 B 两个链表的指针能同时访问到交点。
C
CyC2018 已提交
2363 2364

```java
C
CyC2018 已提交
2365
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
C
CyC2018 已提交
2366 2367 2368 2369 2370 2371
    ListNode l1 = pHead1, l2 = pHead2;
    while (l1 != l2) {
        l1 = (l1 == null) ? pHead2 : l1.next;
        l2 = (l2 == null) ? pHead1 : l2.next;
    }
    return l1;
C
CyC2018 已提交
2372 2373 2374
}
```

C
CyC2018 已提交
2375
# 53 数字在排序数组中出现的次数
C
CyC2018 已提交
2376

C
CyC2018 已提交
2377 2378
[NowCoder](https://www.nowcoder.com/practice/70610bf967994b22bb1c26f9ae901fa2?tpId=13&tqId=11190&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking)

C
CyC2018 已提交
2379
## 题目描述
C
CyC2018 已提交
2380 2381 2382

```html
Input:
C
CyC2018 已提交
2383
1, 2, 3, 3, 3, 3, 4, 6
C
CyC2018 已提交
2384 2385 2386 2387 2388
3
Output:
4
```

C
CyC2018 已提交
2389
## 解题思路
C
CyC2018 已提交
2390 2391

```java
C
CyC2018 已提交
2392
public int GetNumberOfK(int[] nums, int K) {
C
CyC2018 已提交
2393 2394 2395
    int first = binarySearch(nums, K);
    int last = binarySearch(nums, K + 1);
    return (first == nums.length || nums[first] != K) ? 0 : last - first;
C
CyC2018 已提交
2396 2397
}

C
CyC2018 已提交
2398
private int binarySearch(int[] nums, int K) {
C
CyC2018 已提交
2399 2400 2401 2402 2403 2404 2405 2406 2407
    int l = 0, h = nums.length;
    while (l < h) {
        int m = l + (h - l) / 2;
        if (nums[m] >= K)
            h = m;
        else
            l = m + 1;
    }
    return l;
C
CyC2018 已提交
2408 2409 2410
}
```

C
CyC2018 已提交
2411
# 54. 二叉搜索树的第 K 个结点
C
CyC2018 已提交
2412

C
CyC2018 已提交
2413 2414
[NowCoder](https://www.nowcoder.com/practice/ef068f602dde4d28aab2b210e859150a?tpId=13&tqId=11215&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking)

C
CyC2018 已提交
2415
## 解题思路
C
CyC2018 已提交
2416 2417 2418 2419

利用二叉搜索数中序遍历有序的特点。

```java
C
CyC2018 已提交
2420 2421
private TreeNode ret;
private int cnt = 0;
C
CyC2018 已提交
2422

C
CyC2018 已提交
2423
public TreeNode KthNode(TreeNode pRoot, int k) {
C
CyC2018 已提交
2424 2425
    inOrder(pRoot, k);
    return ret;
C
CyC2018 已提交
2426 2427
}

C
CyC2018 已提交
2428
private void inOrder(TreeNode root, int k) {
C
CyC2018 已提交
2429 2430 2431 2432 2433 2434 2435
    if (root == null || cnt >= k)
        return;
    inOrder(root.left, k);
    cnt++;
    if (cnt == k)
        ret = root;
    inOrder(root.right, k);
C
CyC2018 已提交
2436 2437 2438
}
```

C
CyC2018 已提交
2439
# 55.1 二叉树的深度
C
CyC2018 已提交
2440

C
CyC2018 已提交
2441 2442
[NowCoder](https://www.nowcoder.com/practice/435fb86331474282a3499955f0a41e8b?tpId=13&tqId=11191&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking)

C
CyC2018 已提交
2443
## 题目描述
C
CyC2018 已提交
2444 2445 2446

从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。

C
CyC2018 已提交
2447
<div align="center"> <img src="../pics//b29f8971-9cb8-480d-b986-0e60c2ece069.png" width="350"/> </div><br>
C
CyC2018 已提交
2448

C
CyC2018 已提交
2449
## 解题思路
C
CyC2018 已提交
2450 2451

```java
C
CyC2018 已提交
2452
public int TreeDepth(TreeNode root) {
C
CyC2018 已提交
2453
    return root == null ? 0 : 1 + Math.max(TreeDepth(root.left), TreeDepth(root.right));
C
CyC2018 已提交
2454 2455 2456
}
```

C
CyC2018 已提交
2457
# 55.2 平衡二叉树
C
CyC2018 已提交
2458

C
CyC2018 已提交
2459 2460
[NowCoder](https://www.nowcoder.com/practice/8b3b95850edb4115918ecebdf1b4d222?tpId=13&tqId=11192&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking)

C
CyC2018 已提交
2461
## 题目描述
C
CyC2018 已提交
2462

C
CyC2018 已提交
2463
平衡二叉树左右子树高度差不超过 1。
C
CyC2018 已提交
2464

C
CyC2018 已提交
2465
<div align="center"> <img src="../pics//e026c24d-00fa-4e7c-97a8-95a98cdc383a.png" width="300"/> </div><br>
C
CyC2018 已提交
2466

C
CyC2018 已提交
2467
## 解题思路
C
CyC2018 已提交
2468 2469

```java
C
CyC2018 已提交
2470
private boolean isBalanced = true;
C
CyC2018 已提交
2471

C
CyC2018 已提交
2472
public boolean IsBalanced_Solution(TreeNode root) {
C
CyC2018 已提交
2473 2474
    height(root);
    return isBalanced;
C
CyC2018 已提交
2475 2476
}

C
CyC2018 已提交
2477
private int height(TreeNode root) {
C
CyC2018 已提交
2478
    if (root == null || !isBalanced)
C
CyC2018 已提交
2479 2480 2481 2482 2483 2484
        return 0;
    int left = height(root.left);
    int right = height(root.right);
    if (Math.abs(left - right) > 1)
        isBalanced = false;
    return 1 + Math.max(left, right);
C
CyC2018 已提交
2485 2486 2487
}
```

C
CyC2018 已提交
2488
# 56. 数组中只出现一次的数字
C
CyC2018 已提交
2489

C
CyC2018 已提交
2490 2491
[NowCoder](https://www.nowcoder.com/practice/e02fdb54d7524710a7d664d082bb7811?tpId=13&tqId=11193&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking)

C
CyC2018 已提交
2492
## 题目描述
C
CyC2018 已提交
2493

C
CyC2018 已提交
2494 2495
一个整型数组里除了两个数字之外,其他的数字都出现了两次,找出这两个数。

C
CyC2018 已提交
2496
## 解题思路
C
CyC2018 已提交
2497

C
CyC2018 已提交
2498
两个不相等的元素在位级表示上必定会有一位存在不同,将数组的所有元素异或得到的结果为不存在重复的两个元素异或的结果。
C
CyC2018 已提交
2499

C
CyC2018 已提交
2500
diff &= -diff 得到出 diff 最右侧不为 0 的位,也就是不存在重复的两个元素在位级表示上最右侧不同的那一位,利用这一位就可以将两个元素区分开来。
C
CyC2018 已提交
2501 2502

```java
C
CyC2018 已提交
2503
public void FindNumsAppearOnce(int[] nums, int num1[], int num2[]) {
C
CyC2018 已提交
2504 2505 2506 2507 2508 2509 2510 2511 2512
    int diff = 0;
    for (int num : nums)
        diff ^= num;
    diff &= -diff;
    for (int num : nums) {
        if ((num & diff) == 0)
            num1[0] ^= num;
        else
            num2[0] ^= num;
C
CyC2018 已提交
2513
    }
C
CyC2018 已提交
2514
}
C
CyC2018 已提交
2515 2516
```

C
CyC2018 已提交
2517
# 57.1 和为 S 的两个数字
C
CyC2018 已提交
2518

C
CyC2018 已提交
2519 2520
[NowCoder](https://www.nowcoder.com/practice/390da4f7a00f44bea7c2f3d19491311b?tpId=13&tqId=11195&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking)

C
CyC2018 已提交
2521
## 题目描述
C
CyC2018 已提交
2522

C
CyC2018 已提交
2523
输入一个递增排序的数组和一个数字 S,在数组中查找两个数,使得他们的和正好是 S。如果有多对数字的和等于 S,输出两个数的乘积最小的。
C
CyC2018 已提交
2524

C
CyC2018 已提交
2525
## 解题思路
C
CyC2018 已提交
2526 2527 2528

使用双指针,一个指针指向元素较小的值,一个指针指向元素较大的值。指向较小元素的指针从头向尾遍历,指向较大元素的指针从尾向头遍历。

C
CyC2018 已提交
2529 2530 2531
- 如果两个指针指向元素的和 sum == target,那么得到要求的结果;
- 如果 sum > target,移动较大的元素,使 sum 变小一些;
- 如果 sum < target,移动较小的元素,使 sum 变大一些。
C
CyC2018 已提交
2532 2533

```java
C
CyC2018 已提交
2534
public ArrayList<Integer> FindNumbersWithSum(int[] array, int sum) {
C
CyC2018 已提交
2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545
    int i = 0, j = array.length - 1;
    while (i < j) {
        int cur = array[i] + array[j];
        if (cur == sum)
            return new ArrayList<>(Arrays.asList(array[i], array[j]));
        if (cur < sum)
            i++;
        else
            j--;
    }
    return new ArrayList<>();
C
CyC2018 已提交
2546 2547 2548
}
```

C
CyC2018 已提交
2549
# 57.2 和为 S 的连续正数序列
C
CyC2018 已提交
2550

C
CyC2018 已提交
2551 2552
[NowCoder](https://www.nowcoder.com/practice/c451a3fd84b64cb19485dad758a55ebe?tpId=13&tqId=11194&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking)

C
CyC2018 已提交
2553
## 题目描述
C
CyC2018 已提交
2554

C
CyC2018 已提交
2555
输出所有和为 S 的连续正数序列。
C
CyC2018 已提交
2556

C
CyC2018 已提交
2557
例如和为 100 的连续序列有:
C
CyC2018 已提交
2558 2559

```
C
CyC2018 已提交
2560 2561
[9, 10, 11, 12, 13, 14, 15, 16]
[18, 19, 20, 21, 22]。
C
CyC2018 已提交
2562
```
C
CyC2018 已提交
2563

C
CyC2018 已提交
2564
## 解题思路
C
CyC2018 已提交
2565 2566

```java
C
CyC2018 已提交
2567
public ArrayList<ArrayList<Integer>> FindContinuousSequence(int sum) {
C
CyC2018 已提交
2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589
    ArrayList<ArrayList<Integer>> ret = new ArrayList<>();
    int start = 1, end = 2;
    int curSum = 3;
    while (end < sum) {
        if (curSum > sum) {
            curSum -= start;
            start++;
        } else if (curSum < sum) {
            end++;
            curSum += end;
        } else {
            ArrayList<Integer> list = new ArrayList<>();
            for (int i = start; i <= end; i++)
                list.add(i);
            ret.add(list);
            curSum -= start;
            start++;
            end++;
            curSum += end;
        }
    }
    return ret;
C
CyC2018 已提交
2590 2591 2592
}
```

C
CyC2018 已提交
2593
# 58.1 翻转单词顺序列
C
CyC2018 已提交
2594

C
CyC2018 已提交
2595 2596
[NowCoder](https://www.nowcoder.com/practice/3194a4f4cf814f63919d0790578d51f3?tpId=13&tqId=11197&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking)

C
CyC2018 已提交
2597
## 题目描述
C
CyC2018 已提交
2598

C
CyC2018 已提交
2599 2600 2601
```html
Input:
"I am a student."
C
CyC2018 已提交
2602

C
CyC2018 已提交
2603 2604 2605
Output:
"student. a am I"
```
C
CyC2018 已提交
2606

C
CyC2018 已提交
2607
## 解题思路
C
CyC2018 已提交
2608

C
CyC2018 已提交
2609
题目应该有一个隐含条件,就是不能用额外的空间。虽然 Java 的题目输入参数为 String 类型,需要先创建一个字符数组使得空间复杂度为 O(N),但是正确的参数类型应该和原书一样,为字符数组,并且只能使用该字符数组的空间。任何使用了额外空间的解法在面试时都会大打折扣,包括递归解法。
C
CyC2018 已提交
2610 2611

正确的解法应该是和书上一样,先旋转每个单词,再旋转整个字符串。
C
CyC2018 已提交
2612 2613

```java
C
CyC2018 已提交
2614
public String ReverseSentence(String str) {
C
CyC2018 已提交
2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626
    int n = str.length();
    char[] chars = str.toCharArray();
    int i = 0, j = 0;
    while (j <= n) {
        if (j == n || chars[j] == ' ') {
            reverse(chars, i, j - 1);
            i = j + 1;
        }
        j++;
    }
    reverse(chars, 0, n - 1);
    return new String(chars);
C
CyC2018 已提交
2627 2628
}

C
CyC2018 已提交
2629
private void reverse(char[] c, int i, int j) {
C
CyC2018 已提交
2630 2631
    while (i < j)
        swap(c, i++, j--);
C
CyC2018 已提交
2632
}
C
CyC2018 已提交
2633

C
CyC2018 已提交
2634
private void swap(char[] c, int i, int j) {
C
CyC2018 已提交
2635 2636 2637
    char t = c[i];
    c[i] = c[j];
    c[j] = t;
C
CyC2018 已提交
2638
}
C
CyC2018 已提交
2639 2640
```

C
CyC2018 已提交
2641
# 58.2 左旋转字符串
C
CyC2018 已提交
2642

C
CyC2018 已提交
2643 2644
[NowCoder](https://www.nowcoder.com/practice/12d959b108cb42b1ab72cef4d36af5ec?tpId=13&tqId=11196&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking)

C
CyC2018 已提交
2645
## 题目描述
C
CyC2018 已提交
2646

C
CyC2018 已提交
2647 2648 2649 2650 2651 2652 2653 2654
```html
Input:
S="abcXYZdef"
K=3

Output:
"XYZdefabc"
```
C
CyC2018 已提交
2655

C
CyC2018 已提交
2656
## 解题思路
C
CyC2018 已提交
2657

C
CyC2018 已提交
2658
先将 "abc" 和 "XYZdef" 分别翻转,得到 "cbafedZYX",然后再把整个字符串翻转得到 "XYZdefabc"。
C
CyC2018 已提交
2659

C
CyC2018 已提交
2660
```java
C
CyC2018 已提交
2661
public String LeftRotateString(String str, int n) {
C
CyC2018 已提交
2662 2663 2664 2665 2666 2667 2668
    if (n >= str.length())
        return str;
    char[] chars = str.toCharArray();
    reverse(chars, 0, n - 1);
    reverse(chars, n, chars.length - 1);
    reverse(chars, 0, chars.length - 1);
    return new String(chars);
C
CyC2018 已提交
2669 2670
}

C
CyC2018 已提交
2671
private void reverse(char[] chars, int i, int j) {
C
CyC2018 已提交
2672 2673
    while (i < j)
        swap(chars, i++, j--);
C
CyC2018 已提交
2674
}
C
CyC2018 已提交
2675

C
CyC2018 已提交
2676
private void swap(char[] chars, int i, int j) {
C
CyC2018 已提交
2677 2678 2679
    char t = chars[i];
    chars[i] = chars[j];
    chars[j] = t;
C
CyC2018 已提交
2680
}
C
CyC2018 已提交
2681 2682
```

C
CyC2018 已提交
2683
# 59. 滑动窗口的最大值
C
CyC2018 已提交
2684

C
CyC2018 已提交
2685 2686
[NowCoder](https://www.nowcoder.com/practice/1624bc35a45c42c0bc17d17fa0cba788?tpId=13&tqId=11217&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking)

C
CyC2018 已提交
2687
## 题目描述
C
CyC2018 已提交
2688

C
CyC2018 已提交
2689 2690 2691
给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。

例如,如果输入数组 {2, 3, 4, 2, 6, 2, 5, 1} 及滑动窗口的大小 3,那么一共存在 6 个滑动窗口,他们的最大值分别为 {4, 4, 6, 6, 6, 5}。
C
CyC2018 已提交
2692

C
CyC2018 已提交
2693
## 解题思路
C
CyC2018 已提交
2694 2695

```java
C
CyC2018 已提交
2696
public ArrayList<Integer> maxInWindows(int[] num, int size) {
C
CyC2018 已提交
2697 2698 2699
    ArrayList<Integer> ret = new ArrayList<>();
    if (size > num.length || size < 1)
        return ret;
C
CyC2018 已提交
2700
    PriorityQueue<Integer> heap = new PriorityQueue<>((o1, o2) -> o2 - o1);  /* 大顶堆 */
C
CyC2018 已提交
2701 2702 2703
    for (int i = 0; i < size; i++)
        heap.add(num[i]);
    ret.add(heap.peek());
C
CyC2018 已提交
2704
    for (int i = 1, j = i + size - 1; j < num.length; i++, j++) {            /* 维护一个大小为 size 的大顶堆 */
C
CyC2018 已提交
2705 2706 2707 2708 2709
        heap.remove(num[i - 1]);
        heap.add(num[j]);
        ret.add(heap.peek());
    }
    return ret;
C
CyC2018 已提交
2710 2711 2712
}
```

C
CyC2018 已提交
2713
# 60. n 个骰子的点数
C
CyC2018 已提交
2714

C
CyC2018 已提交
2715 2716
[Lintcode](https://www.lintcode.com/en/problem/dices-sum/)

C
CyC2018 已提交
2717
## 题目描述
C
CyC2018 已提交
2718

C
CyC2018 已提交
2719
把 n 个骰子仍在地上,求点数和为 s 的概率。
C
CyC2018 已提交
2720

C
CyC2018 已提交
2721
## 解题思路
C
CyC2018 已提交
2722

C
CyC2018 已提交
2723
### 动态规划解法
C
CyC2018 已提交
2724

C
CyC2018 已提交
2725
使用一个二维数组 dp 存储点数出现的次数,其中 dp[i][j] 表示前 i 个骰子产生点数 j 的次数。
C
CyC2018 已提交
2726

C
CyC2018 已提交
2727 2728 2729
空间复杂度:O(N<sup>2</sup>)

```java
C
CyC2018 已提交
2730
public List<Map.Entry<Integer, Double>> dicesSum(int n) {
C
CyC2018 已提交
2731 2732 2733
    final int face = 6;
    final int pointNum = face * n;
    long[][] dp = new long[n + 1][pointNum + 1];
C
CyC2018 已提交
2734

C
CyC2018 已提交
2735 2736
    for (int i = 1; i <= face; i++)
        dp[1][i] = 1;
C
CyC2018 已提交
2737

C
CyC2018 已提交
2738
    for (int i = 2; i <= n; i++)
C
CyC2018 已提交
2739
        for (int j = i; j <= pointNum; j++)     /* 使用 i 个骰子最小点数为 i */
C
CyC2018 已提交
2740 2741
            for (int k = 1; k <= face && k <= j; k++)
                dp[i][j] += dp[i - 1][j - k];
C
CyC2018 已提交
2742

C
CyC2018 已提交
2743 2744 2745 2746
    final double totalNum = Math.pow(6, n);
    List<Map.Entry<Integer, Double>> ret = new ArrayList<>();
    for (int i = n; i <= pointNum; i++)
        ret.add(new AbstractMap.SimpleEntry<>(i, dp[n][i] / totalNum));
C
CyC2018 已提交
2747

C
CyC2018 已提交
2748
    return ret;
C
CyC2018 已提交
2749 2750 2751
}
```

C
CyC2018 已提交
2752
### 动态规划解法 + 旋转数组
C
CyC2018 已提交
2753 2754 2755 2756

空间复杂度:O(N)

```java
C
CyC2018 已提交
2757
public List<Map.Entry<Integer, Double>> dicesSum(int n) {
C
CyC2018 已提交
2758 2759 2760
    final int face = 6;
    final int pointNum = face * n;
    long[][] dp = new long[2][pointNum + 1];
C
CyC2018 已提交
2761

C
CyC2018 已提交
2762 2763
    for (int i = 1; i <= face; i++)
        dp[0][i] = 1;
C
CyC2018 已提交
2764 2765

    int flag = 1;                                     /* 旋转标记 */
C
CyC2018 已提交
2766 2767
    for (int i = 2; i <= n; i++, flag = 1 - flag) {
        for (int j = 0; j <= pointNum; j++)
C
CyC2018 已提交
2768 2769 2770
            dp[flag][j] = 0;                          /* 旋转数组清零 */

        for (int j = i; j <= pointNum; j++)
C
CyC2018 已提交
2771 2772 2773
            for (int k = 1; k <= face && k <= j; k++)
                dp[flag][j] += dp[1 - flag][j - k];
    }
C
CyC2018 已提交
2774

C
CyC2018 已提交
2775 2776 2777 2778
    final double totalNum = Math.pow(6, n);
    List<Map.Entry<Integer, Double>> ret = new ArrayList<>();
    for (int i = n; i <= pointNum; i++)
        ret.add(new AbstractMap.SimpleEntry<>(i, dp[1 - flag][i] / totalNum));
C
CyC2018 已提交
2779

C
CyC2018 已提交
2780
    return ret;
C
CyC2018 已提交
2781 2782 2783
}
```

C
CyC2018 已提交
2784
# 61. 扑克牌顺子
C
CyC2018 已提交
2785

C
CyC2018 已提交
2786 2787
[NowCoder](https://www.nowcoder.com/practice/762836f4d43d43ca9deb273b3de8e1f4?tpId=13&tqId=11198&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking)

C
CyC2018 已提交
2788
## 题目描述
C
CyC2018 已提交
2789

C
CyC2018 已提交
2790
五张牌,其中大小鬼为癞子,牌面大小为 0。判断这五张牌是否能组成顺子。
C
CyC2018 已提交
2791

C
CyC2018 已提交
2792
## 解题思路
C
CyC2018 已提交
2793 2794

```java
C
CyC2018 已提交
2795
public boolean isContinuous(int[] nums) {
C
CyC2018 已提交
2796 2797 2798 2799
    if (nums.length < 5)
        return false;
    Arrays.sort(nums);
    int cnt = 0;
C
CyC2018 已提交
2800
    for (int num : nums)                   /* 统计癞子数量 */
C
CyC2018 已提交
2801 2802
        if (num == 0)
            cnt++;
C
CyC2018 已提交
2803

C
CyC2018 已提交
2804 2805 2806
    for (int i = cnt; i < nums.length - 1; i++) {
        if (nums[i + 1] == nums[i])
            return false;
C
CyC2018 已提交
2807
        cnt -= nums[i + 1] - nums[i] - 1;  /* 使用癞子去补全不连续的顺子 */
C
CyC2018 已提交
2808 2809
    }
    return cnt >= 0;
C
CyC2018 已提交
2810 2811 2812
}
```

C
CyC2018 已提交
2813
# 62. 圆圈中最后剩下的数
C
CyC2018 已提交
2814

C
CyC2018 已提交
2815 2816
[NowCoder](https://www.nowcoder.com/practice/f78a359491e64a50bce2d89cff857eb6?tpId=13&tqId=11199&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking)

C
CyC2018 已提交
2817
## 题目描述
C
CyC2018 已提交
2818

C
CyC2018 已提交
2819
让小朋友们围成一个大圈。然后,随机指定一个数 m,让编号为 0 的小朋友开始报数。每次喊到 m-1 的那个小朋友要出列唱首歌,然后可以在礼品箱中任意的挑选礼物,并且不再回到圈中,从他的下一个小朋友开始,继续 0...m-1 报数 .... 这样下去 .... 直到剩下最后一个小朋友,可以不用表演。
C
CyC2018 已提交
2820

C
CyC2018 已提交
2821
## 解题思路
C
CyC2018 已提交
2822

C
CyC2018 已提交
2823
约瑟夫环,圆圈长度为 n 的解可以看成长度为 n-1 的解再加上报数的长度 m。因为是圆圈,所以最后需要对 n 取余。
C
CyC2018 已提交
2824 2825

```java
C
CyC2018 已提交
2826
public int LastRemaining_Solution(int n, int m) {
C
CyC2018 已提交
2827
    if (n == 0)     /* 特殊输入的处理 */
C
CyC2018 已提交
2828
        return -1;
C
CyC2018 已提交
2829
    if (n == 1)     /* 递归返回条件 */
C
CyC2018 已提交
2830 2831
        return 0;
    return (LastRemaining_Solution(n - 1, m) + m) % n;
C
CyC2018 已提交
2832 2833 2834
}
```

C
CyC2018 已提交
2835
# 63. 股票的最大利润
C
CyC2018 已提交
2836

C
CyC2018 已提交
2837 2838
[Leetcode](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/)

C
CyC2018 已提交
2839
## 题目描述
C
CyC2018 已提交
2840

C
CyC2018 已提交
2841 2842
可以有一次买入和一次卖出,买入必须在前。求最大收益。

C
CyC2018 已提交
2843
## 解题思路
C
CyC2018 已提交
2844

C
CyC2018 已提交
2845
使用贪心策略,假设第 i 轮进行卖出操作,买入操作价格应该在 i 之前并且价格最低。
C
CyC2018 已提交
2846 2847

```java
C
CyC2018 已提交
2848
public int maxProfit(int[] prices) {
C
CyC2018 已提交
2849 2850 2851 2852
    if (prices == null || prices.length == 0)
        return 0;
    int soFarMin = prices[0];
    int maxProfit = 0;
C
CyC2018 已提交
2853
    for (int i = 1; i < prices.length; i++) {
C
CyC2018 已提交
2854 2855 2856 2857
        soFarMin = Math.min(soFarMin, prices[i]);
        maxProfit = Math.max(maxProfit, prices[i] - soFarMin);
    }
    return maxProfit;
C
CyC2018 已提交
2858 2859 2860
}
```

C
CyC2018 已提交
2861
# 64. 求 1+2+3+...+n
C
CyC2018 已提交
2862

C
CyC2018 已提交
2863 2864
[NowCoder](https://www.nowcoder.com/practice/7a0da8fc483247ff8800059e12d7caf1?tpId=13&tqId=11200&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking)

C
CyC2018 已提交
2865
## 题目描述
C
CyC2018 已提交
2866

C
CyC2018 已提交
2867
要求不能使用乘除法、for、while、if、else、switch、case 等关键字及条件判断语句 A ? B : C。
C
CyC2018 已提交
2868

C
CyC2018 已提交
2869
## 解题思路
C
CyC2018 已提交
2870

C
CyC2018 已提交
2871
使用递归解法最重要的是指定返回条件,但是本题无法直接使用 if 语句来指定返回条件。
C
CyC2018 已提交
2872

C
CyC2018 已提交
2873
条件与 && 具有短路原则,即在第一个条件语句为 false 的情况下不会去执行第二个条件语句。利用这一特性,将递归的返回条件取非然后作为 && 的第一个条件语句,递归的主体转换为第二个条件语句,那么当递归的返回条件为 true 的情况下就不会执行递归的主体部分,递归返回。
C
CyC2018 已提交
2874

C
CyC2018 已提交
2875
本题的递归返回条件为 n <= 0,取非后就是 n > 0;递归的主体部分为 sum += Sum_Solution(n - 1),转换为条件语句后就是 (sum += Sum_Solution(n - 1)) > 0。
C
CyC2018 已提交
2876

C
CyC2018 已提交
2877
```java
C
CyC2018 已提交
2878
public int Sum_Solution(int n) {
C
CyC2018 已提交
2879 2880 2881
    int sum = n;
    boolean b = (n > 0) && ((sum += Sum_Solution(n - 1)) > 0);
    return sum;
C
CyC2018 已提交
2882 2883 2884
}
```

C
CyC2018 已提交
2885
# 65. 不用加减乘除做加法
C
CyC2018 已提交
2886

C
CyC2018 已提交
2887 2888
[NowCoder](https://www.nowcoder.com/practice/59ac416b4b944300b617d4f7f111b215?tpId=13&tqId=11201&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking)

C
CyC2018 已提交
2889
## 题目描述
C
CyC2018 已提交
2890

C
CyC2018 已提交
2891
写一个函数,求两个整数之和,要求不得使用 +、-、\*、/ 四则运算符号。
C
CyC2018 已提交
2892

C
CyC2018 已提交
2893
## 解题思路
C
CyC2018 已提交
2894

C
CyC2018 已提交
2895
a ^ b 表示没有考虑进位的情况下两数的和,(a & b) << 1 就是进位。
C
CyC2018 已提交
2896

C
CyC2018 已提交
2897
递归会终止的原因是 (a & b) << 1 最右边会多一个 0,那么继续递归,进位最右边的 0 会慢慢增多,最后进位会变为 0,递归终止。
C
CyC2018 已提交
2898 2899

```java
C
CyC2018 已提交
2900
public int Add(int a, int b) {
C
CyC2018 已提交
2901
    return b == 0 ? a : Add(a ^ b, (a & b) << 1);
C
CyC2018 已提交
2902 2903 2904
}
```

C
CyC2018 已提交
2905
# 66. 构建乘积数组
C
CyC2018 已提交
2906

C
CyC2018 已提交
2907 2908
[NowCoder](https://www.nowcoder.com/practice/94a4d381a68b47b7a8bed86f2975db46?tpId=13&tqId=11204&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking)

C
CyC2018 已提交
2909
## 题目描述
C
CyC2018 已提交
2910

C
CyC2018 已提交
2911
给定一个数组 A[0, 1,..., n-1],请构建一个数组 B[0, 1,..., n-1],其中 B 中的元素 B[i]=A[0]\*A[1]\*...\*A[i-1]\*A[i+1]\*...\*A[n-1]。要求不能使用除法。
C
CyC2018 已提交
2912

C
CyC2018 已提交
2913
## 解题思路
C
CyC2018 已提交
2914 2915

```java
C
CyC2018 已提交
2916
public int[] multiply(int[] A) {
C
CyC2018 已提交
2917 2918
    int n = A.length;
    int[] B = new int[n];
C
CyC2018 已提交
2919
    for (int i = 0, product = 1; i < n; product *= A[i], i++)       /* 从左往右累乘 */
C
CyC2018 已提交
2920
        B[i] = product;
C
CyC2018 已提交
2921
    for (int i = n - 1, product = 1; i >= 0; product *= A[i], i--)  /* 从右往左累乘 */
C
CyC2018 已提交
2922 2923
        B[i] *= product;
    return B;
C
CyC2018 已提交
2924 2925 2926
}
```

C
CyC2018 已提交
2927
# 67. 把字符串转换成整数
C
CyC2018 已提交
2928

C
CyC2018 已提交
2929 2930
[NowCoder](https://www.nowcoder.com/practice/1277c681251b4372bdef344468e4f26e?tpId=13&tqId=11202&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking)

C
CyC2018 已提交
2931
## 题目描述
C
CyC2018 已提交
2932

C
CyC2018 已提交
2933
将一个字符串转换成一个整数,字符串不是一个合法的数值则返回 0,要求不能使用字符串转换整数的库函数。
C
CyC2018 已提交
2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944

```html
Iuput:
+2147483647
1a33

Output:
2147483647
0
```

C
CyC2018 已提交
2945
## 解题思路
C
CyC2018 已提交
2946 2947

```java
C
CyC2018 已提交
2948
public int StrToInt(String str) {
C
CyC2018 已提交
2949 2950 2951 2952 2953 2954
    if (str == null || str.length() == 0)
        return 0;
    boolean isNegative = str.charAt(0) == '-';
    int ret = 0;
    for (int i = 0; i < str.length(); i++) {
        char c = str.charAt(i);
C
CyC2018 已提交
2955
        if (i == 0 && (c == '+' || c == '-'))  /* 符号判定 */
C
CyC2018 已提交
2956
            continue;
C
CyC2018 已提交
2957 2958
        if (c < '0' || c > '9')                /* 非法输入 */
            return 0;
C
CyC2018 已提交
2959 2960 2961
        ret = ret * 10 + (c - '0');
    }
    return isNegative ? -ret : ret;
C
CyC2018 已提交
2962 2963 2964
}
```

C
CyC2018 已提交
2965
# 68. 树中两个节点的最低公共祖先
C
CyC2018 已提交
2966

C
CyC2018 已提交
2967
## 解题思路
C
CyC2018 已提交
2968

C
CyC2018 已提交
2969
### 二叉查找树
C
CyC2018 已提交
2970

C
CyC2018 已提交
2971
<div align="center"> <img src="../pics//293d2af9-de1d-403e-bed0-85d029383528.png" width="300"/> </div><br>
C
CyC2018 已提交
2972

C
CyC2018 已提交
2973
[Leetcode : 235. Lowest Common Ancestor of a Binary Search Tree](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/description/)
C
CyC2018 已提交
2974

C
CyC2018 已提交
2975
二叉查找树中,两个节点 p, q 的公共祖先 root 满足 root.val >= p.val && root.val <= q.val。
C
CyC2018 已提交
2976 2977

```java
C
CyC2018 已提交
2978 2979 2980 2981 2982 2983 2984 2985
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
    if (root == null)
        return root;
    if (root.val > p.val && root.val > q.val)
        return lowestCommonAncestor(root.left, p, q);
    if (root.val < p.val && root.val < q.val)
        return lowestCommonAncestor(root.right, p, q);
    return root;
C
CyC2018 已提交
2986 2987 2988
}
```

C
CyC2018 已提交
2989
### 普通二叉树
C
CyC2018 已提交
2990

C
CyC2018 已提交
2991
<div align="center"> <img src="../pics//37a72755-4890-4b42-9eab-b0084e0c54d9.png" width="300"/> </div><br>
C
CyC2018 已提交
2992

C
CyC2018 已提交
2993
[Leetcode : 236. Lowest Common Ancestor of a Binary Tree](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/description/)
C
CyC2018 已提交
2994

C
CyC2018 已提交
2995
在左右子树中查找是否存在 p 或者 q,如果 p 和 q 分别在两个子树中,那么就说明根节点就是最低公共祖先。
C
CyC2018 已提交
2996 2997

```java
C
CyC2018 已提交
2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
    if (root == null || root == p || root == q)
        return root;
    TreeNode left = lowestCommonAncestor(root.left, p, q);
    TreeNode right = lowestCommonAncestor(root.right, p, q);
    return left == null ? right : right == null ? left : root;
}
```

# 参考文献

- 何海涛. 剑指 Offer[M]. 电子工业出版社, 2012.