Leetcode 题解.md 191.9 KB
Newer Older
C
CyC2018 已提交
1
* [点击阅读面试进阶指南 ](https://github.com/CyC2018/Backend-Interview-Guide)
C
CyC2018 已提交
2 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
<!-- GFM-TOC -->
* [算法思想](#算法思想)
    * [双指针](#双指针)
    * [排序](#排序)
        * [快速选择](#快速选择)
        * [堆排序](#堆排序)
        * [桶排序](#桶排序)
        * [荷兰国旗问题](#荷兰国旗问题)
    * [贪心思想](#贪心思想)
    * [二分查找](#二分查找)
    * [分治](#分治)
    * [搜索](#搜索)
        * [BFS](#bfs)
        * [DFS](#dfs)
        * [Backtracking](#backtracking)
    * [动态规划](#动态规划)
        * [斐波那契数列](#斐波那契数列)
        * [矩阵路径](#矩阵路径)
        * [数组区间](#数组区间)
        * [分割整数](#分割整数)
        * [最长递增子序列](#最长递增子序列)
        * [最长公共子序列](#最长公共子序列)
        * [0-1 背包](#0-1-背包)
        * [股票交易](#股票交易)
        * [字符串编辑](#字符串编辑)
    * [数学](#数学)
        * [素数](#素数)
        * [最大公约数](#最大公约数)
        * [进制转换](#进制转换)
        * [阶乘](#阶乘)
        * [字符串加法减法](#字符串加法减法)
        * [相遇问题](#相遇问题)
        * [多数投票问题](#多数投票问题)
        * [其它](#其它)
* [数据结构相关](#数据结构相关)
    * [链表](#链表)
    * [](#树)
        * [递归](#递归)
        * [层次遍历](#层次遍历)
        * [前中后序遍历](#前中后序遍历)
        * [BST](#bst)
        * [Trie](#trie)
    * [栈和队列](#栈和队列)
    * [哈希表](#哈希表)
    * [字符串](#字符串)
    * [数组与矩阵](#数组与矩阵)
    * [](#图)
        * [二分图](#二分图)
        * [拓扑排序](#拓扑排序)
        * [并查集](#并查集)
    * [位运算](#位运算)
* [参考资料](#参考资料)
<!-- GFM-TOC -->


# 算法思想

## 双指针
C
CyC2018 已提交
60

C
CyC2018 已提交
61
双指针主要用于遍历数组,两个指针指向不同的元素,从而协同完成任务。
C
CyC2018 已提交
62

C
CyC2018 已提交
63
**有序数组的 Two Sum** 
C
CyC2018 已提交
64

C
CyC2018 已提交
65
[Leetcode :167. Two Sum II - Input array is sorted (Easy)](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/description/)
C
CyC2018 已提交
66 67

```html
C
CyC2018 已提交
68 69
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
C
CyC2018 已提交
70
```
C
CyC2018 已提交
71

C
CyC2018 已提交
72
题目描述:在有序数组中找出两个数,使它们的和为 target。
C
CyC2018 已提交
73

C
CyC2018 已提交
74
使用双指针,一个指针指向值较小的元素,一个指针指向值较大的元素。指向较小元素的指针从头向尾遍历,指向较大元素的指针从尾向头遍历。
C
CyC2018 已提交
75

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

```java
C
CyC2018 已提交
81 82 83 84 85 86 87 88 89 90 91 92 93
public int[] twoSum(int[] numbers, int target) {
    int i = 0, j = numbers.length - 1;
    while (i < j) {
        int sum = numbers[i] + numbers[j];
        if (sum == target) {
            return new int[]{i + 1, j + 1};
        } else if (sum < target) {
            i++;
        } else {
            j--;
        }
    }
    return null;
C
CyC2018 已提交
94 95 96
}
```

C
CyC2018 已提交
97
**两数平方和** 
C
CyC2018 已提交
98

C
CyC2018 已提交
99
[633. Sum of Square Numbers (Easy)](https://leetcode.com/problems/sum-of-square-numbers/description/)
C
CyC2018 已提交
100 101

```html
C
CyC2018 已提交
102 103 104
Input: 5
Output: True
Explanation: 1 * 1 + 2 * 2 = 5
C
CyC2018 已提交
105 106
```

C
CyC2018 已提交
107
题目描述:判断一个数是否为两个数的平方和。
C
CyC2018 已提交
108

C
CyC2018 已提交
109
```java
C
CyC2018 已提交
110 111 112 113 114 115 116 117 118 119 120 121 122
public boolean judgeSquareSum(int c) {
    int i = 0, j = (int) Math.sqrt(c);
    while (i <= j) {
        int powSum = i * i + j * j;
        if (powSum == c) {
            return true;
        } else if (powSum > c) {
            j--;
        } else {
            i++;
        }
    }
    return false;
C
CyC2018 已提交
123
}
C
CyC2018 已提交
124 125
```

C
CyC2018 已提交
126
**反转字符串中的元音字符** 
C
CyC2018 已提交
127

C
CyC2018 已提交
128
[345. Reverse Vowels of a String (Easy)](https://leetcode.com/problems/reverse-vowels-of-a-string/description/)
C
CyC2018 已提交
129

C
CyC2018 已提交
130
```html
C
CyC2018 已提交
131
Given s = "leetcode", return "leotcede".
C
CyC2018 已提交
132
```
C
CyC2018 已提交
133

C
CyC2018 已提交
134
使用双指针指向待反转的两个元音字符,一个指针从头向尾遍历,一个指针从尾到头遍历。
C
CyC2018 已提交
135 136

```java
C
CyC2018 已提交
137
private final static HashSet<Character> vowels = new HashSet<>(Arrays.asList('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'));
C
CyC2018 已提交
138

C
CyC2018 已提交
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
public String reverseVowels(String s) {
    int i = 0, j = s.length() - 1;
    char[] result = new char[s.length()];
    while (i <= j) {
        char ci = s.charAt(i);
        char cj = s.charAt(j);
        if (!vowels.contains(ci)) {
            result[i++] = ci;
        } else if (!vowels.contains(cj)) {
            result[j--] = cj;
        } else {
            result[i++] = cj;
            result[j--] = ci;
        }
    }
    return new String(result);
C
CyC2018 已提交
155 156 157
}
```

C
CyC2018 已提交
158
**回文字符串** 
C
CyC2018 已提交
159

C
CyC2018 已提交
160
[680. Valid Palindrome II (Easy)](https://leetcode.com/problems/valid-palindrome-ii/description/)
C
CyC2018 已提交
161

C
CyC2018 已提交
162
```html
C
CyC2018 已提交
163 164 165
Input: "abca"
Output: True
Explanation: You could delete the character 'c'.
C
CyC2018 已提交
166 167
```

C
CyC2018 已提交
168
题目描述:可以删除一个字符,判断是否能构成回文字符串。
C
CyC2018 已提交
169 170

```java
C
CyC2018 已提交
171 172 173 174 175 176 177 178
public boolean validPalindrome(String s) {
    int i = -1, j = s.length();
    while (++i < --j) {
        if (s.charAt(i) != s.charAt(j)) {
            return isPalindrome(s, i, j - 1) || isPalindrome(s, i + 1, j);
        }
    }
    return true;
C
CyC2018 已提交
179 180
}

C
CyC2018 已提交
181 182 183 184 185 186 187
private boolean isPalindrome(String s, int i, int j) {
    while (i < j) {
        if (s.charAt(i++) != s.charAt(j--)) {
            return false;
        }
    }
    return true;
C
CyC2018 已提交
188 189 190
}
```

C
CyC2018 已提交
191
**归并两个有序数组** 
C
CyC2018 已提交
192

C
CyC2018 已提交
193
[88. Merge Sorted Array (Easy)](https://leetcode.com/problems/merge-sorted-array/description/)
C
CyC2018 已提交
194 195 196

```html
Input:
C
CyC2018 已提交
197 198
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6],       n = 3
C
CyC2018 已提交
199

C
CyC2018 已提交
200
Output: [1,2,2,3,5,6]
C
CyC2018 已提交
201 202
```

C
CyC2018 已提交
203
题目描述:把归并结果存到第一个数组上。
C
CyC2018 已提交
204

C
CyC2018 已提交
205
需要从尾开始遍历,否则在 nums1 上归并得到的值会覆盖还未进行归并比较的值。
C
CyC2018 已提交
206 207

```java
C
CyC2018 已提交
208 209 210 211 212 213 214 215 216 217 218 219 220 221
public void merge(int[] nums1, int m, int[] nums2, int n) {
    int index1 = m - 1, index2 = n - 1;
    int indexMerge = m + n - 1;
    while (index1 >= 0 || index2 >= 0) {
        if (index1 < 0) {
            nums1[indexMerge--] = nums2[index2--];
        } else if (index2 < 0) {
            nums1[indexMerge--] = nums1[index1--];
        } else if (nums1[index1] > nums2[index2]) {
            nums1[indexMerge--] = nums1[index1--];
        } else {
            nums1[indexMerge--] = nums2[index2--];
        }
    }
C
CyC2018 已提交
222 223
}
```
C
CyC2018 已提交
224

C
CyC2018 已提交
225
**判断链表是否存在环** 
C
CyC2018 已提交
226

C
CyC2018 已提交
227
[141. Linked List Cycle (Easy)](https://leetcode.com/problems/linked-list-cycle/description/)
C
CyC2018 已提交
228

C
CyC2018 已提交
229
使用双指针,一个指针每次移动一个节点,一个指针每次移动两个节点,如果存在环,那么这两个指针一定会相遇。
C
CyC2018 已提交
230 231

```java
C
CyC2018 已提交
232 233 234 235 236 237 238 239 240 241 242 243 244
public boolean hasCycle(ListNode head) {
    if (head == null) {
        return false;
    }
    ListNode l1 = head, l2 = head.next;
    while (l1 != null && l2 != null && l2.next != null) {
        if (l1 == l2) {
            return true;
        }
        l1 = l1.next;
        l2 = l2.next.next;
    }
    return false;
C
CyC2018 已提交
245
}
C
CyC2018 已提交
246
```
C
CyC2018 已提交
247

C
CyC2018 已提交
248
**最长子序列** 
C
CyC2018 已提交
249

C
CyC2018 已提交
250
[524. Longest Word in Dictionary through Deleting (Medium)](https://leetcode.com/problems/longest-word-in-dictionary-through-deleting/description/)
C
CyC2018 已提交
251

C
CyC2018 已提交
252 253
```
Input:
C
CyC2018 已提交
254
s = "abpcplea", d = ["ale","apple","monkey","plea"]
C
CyC2018 已提交
255

C
CyC2018 已提交
256 257
Output:
"apple"
C
CyC2018 已提交
258
```
C
CyC2018 已提交
259

C
CyC2018 已提交
260
题目描述:删除 s 中的一些字符,使得它构成字符串列表 d 中的一个字符串,找出能构成的最长字符串。如果有多个相同长度的结果,返回字典序的最小字符串。
C
CyC2018 已提交
261 262

```java
C
CyC2018 已提交
263 264 265 266 267 268 269 270 271 272 273 274
public String findLongestWord(String s, List<String> d) {
    String longestWord = "";
    for (String target : d) {
        int l1 = longestWord.length(), l2 = target.length();
        if (l1 > l2 || (l1 == l2 && longestWord.compareTo(target) < 0)) {
            continue;
        }
        if (isValid(s, target)) {
            longestWord = target;
        }
    }
    return longestWord;
C
CyC2018 已提交
275
}
C
CyC2018 已提交
276

C
CyC2018 已提交
277 278 279 280 281 282 283 284 285
private boolean isValid(String s, String target) {
    int i = 0, j = 0;
    while (i < s.length() && j < target.length()) {
        if (s.charAt(i) == target.charAt(j)) {
            j++;
        }
        i++;
    }
    return j == target.length();
C
CyC2018 已提交
286 287
}
```
C
CyC2018 已提交
288

C
CyC2018 已提交
289
## 排序
C
CyC2018 已提交
290

C
CyC2018 已提交
291
### 快速选择
C
CyC2018 已提交
292

C
CyC2018 已提交
293
用于求解  **Kth Element**  问题,使用快速排序的 partition() 进行实现。
C
CyC2018 已提交
294

C
CyC2018 已提交
295
需要先打乱数组,否则最坏情况下时间复杂度为 O(N<sup>2</sup>)。
C
CyC2018 已提交
296

C
CyC2018 已提交
297
### 堆排序
C
CyC2018 已提交
298

C
CyC2018 已提交
299
用于求解  **TopK Elements**  问题,通过维护一个大小为 K 的堆,堆中的元素就是 TopK Elements。
C
CyC2018 已提交
300

C
CyC2018 已提交
301
堆排序也可以用于求解 Kth Element 问题,堆顶元素就是 Kth Element。
C
CyC2018 已提交
302

C
CyC2018 已提交
303
快速选择也可以求解 TopK Elements 问题,因为找到 Kth Element 之后,再遍历一次数组,所有小于等于 Kth Element 的元素都是 TopK Elements。
C
CyC2018 已提交
304

C
CyC2018 已提交
305
可以看到,快速选择和堆排序都可以求解 Kth Element 和 TopK Elements 问题。
C
CyC2018 已提交
306

C
CyC2018 已提交
307
**Kth Element** 
C
CyC2018 已提交
308

C
CyC2018 已提交
309
[215. Kth Largest Element in an Array (Medium)](https://leetcode.com/problems/kth-largest-element-in-an-array/description/)
C
CyC2018 已提交
310

C
CyC2018 已提交
311
题目描述:找到第 k 大的元素。
C
CyC2018 已提交
312

C
CyC2018 已提交
313
**排序** :时间复杂度 O(NlogN),空间复杂度 O(1)
C
CyC2018 已提交
314 315

```java
C
CyC2018 已提交
316 317 318
public int findKthLargest(int[] nums, int k) {
    Arrays.sort(nums);
    return nums[nums.length - k];
C
CyC2018 已提交
319 320 321
}
```

C
CyC2018 已提交
322
**堆排序** :时间复杂度 O(NlogK),空间复杂度 O(K)。
C
CyC2018 已提交
323

C
CyC2018 已提交
324
```java
C
CyC2018 已提交
325 326 327 328 329 330 331 332
public int findKthLargest(int[] nums, int k) {
    PriorityQueue<Integer> pq = new PriorityQueue<>(); // 小顶堆
    for (int val : nums) {
        pq.add(val);
        if (pq.size() > k)  // 维护堆的大小为 K
            pq.poll();
    }
    return pq.peek();
C
CyC2018 已提交
333
}
C
CyC2018 已提交
334 335
```

C
CyC2018 已提交
336
**快速选择** :时间复杂度 O(N),空间复杂度 O(1)
C
CyC2018 已提交
337 338

```java
C
CyC2018 已提交
339 340 341 342 343 344 345 346 347 348 349 350 351 352
public int findKthLargest(int[] nums, int k) {
    k = nums.length - k;
    int l = 0, h = nums.length - 1;
    while (l < h) {
        int j = partition(nums, l, h);
        if (j == k) {
            break;
        } else if (j < k) {
            l = j + 1;
        } else {
            h = j - 1;
        }
    }
    return nums[k];
C
CyC2018 已提交
353
}
C
CyC2018 已提交
354

C
CyC2018 已提交
355 356 357 358 359 360 361 362 363 364 365 366
private int partition(int[] a, int l, int h) {
    int i = l, j = h + 1;
    while (true) {
        while (a[++i] < a[l] && i < h) ;
        while (a[--j] > a[l] && j > l) ;
        if (i >= j) {
            break;
        }
        swap(a, i, j);
    }
    swap(a, l, j);
    return j;
C
CyC2018 已提交
367 368
}

C
CyC2018 已提交
369 370 371 372
private void swap(int[] a, int i, int j) {
    int t = a[i];
    a[i] = a[j];
    a[j] = t;
C
CyC2018 已提交
373 374 375
}
```

C
CyC2018 已提交
376
### 桶排序
C
CyC2018 已提交
377

C
CyC2018 已提交
378
**出现频率最多的 k 个数** 
C
CyC2018 已提交
379

C
CyC2018 已提交
380
[347. Top K Frequent Elements (Medium)](https://leetcode.com/problems/top-k-frequent-elements/description/)
C
CyC2018 已提交
381 382

```html
C
CyC2018 已提交
383
Given [1,1,1,2,2,3] and k = 2, return [1,2].
C
CyC2018 已提交
384 385
```

C
CyC2018 已提交
386
设置若干个桶,每个桶存储出现频率相同的数,并且桶的下标代表桶中数出现的频率,即第 i 个桶中存储的数出现的频率为 i。
C
CyC2018 已提交
387

C
CyC2018 已提交
388
把数都放到桶之后,从后向前遍历桶,最先得到的 k 个数就是出现频率最多的的 k 个数。
C
CyC2018 已提交
389

C
CyC2018 已提交
390
```java
C
CyC2018 已提交
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405
public List<Integer> topKFrequent(int[] nums, int k) {
    Map<Integer, Integer> frequencyForNum = new HashMap<>();
    for (int num : nums) {
        frequencyForNum.put(num, frequencyForNum.getOrDefault(num, 0) + 1);
    }
    List<Integer>[] buckets = new ArrayList[nums.length + 1];
    for (int key : frequencyForNum.keySet()) {
        int frequency = frequencyForNum.get(key);
        if (buckets[frequency] == null) {
            buckets[frequency] = new ArrayList<>();
        }
        buckets[frequency].add(key);
    }
    List<Integer> topK = new ArrayList<>();
    for (int i = buckets.length - 1; i >= 0 && topK.size() < k; i--) {
C
CyC2018 已提交
406 407 408
        if (buckets[i] == null) {
            continue;
        }
C
CyC2018 已提交
409 410 411 412
        if (buckets[i].size() <= (k - topK.size())) {
            topK.addAll(buckets[i]);
        } else {
            topK.addAll(buckets[i].subList(0, k - topK.size()));
C
CyC2018 已提交
413 414 415
        }
    }
    return topK;
C
CyC2018 已提交
416 417 418
}
```

C
CyC2018 已提交
419
**按照字符出现次数对字符串排序** 
C
CyC2018 已提交
420

C
CyC2018 已提交
421
[451. Sort Characters By Frequency (Medium)](https://leetcode.com/problems/sort-characters-by-frequency/description/)
C
CyC2018 已提交
422 423

```html
C
CyC2018 已提交
424 425
Input:
"tree"
C
CyC2018 已提交
426

C
CyC2018 已提交
427 428
Output:
"eert"
C
CyC2018 已提交
429 430

Explanation:
C
CyC2018 已提交
431 432
'e' appears twice while 'r' and 't' both appear once.
So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer.
C
CyC2018 已提交
433 434 435
```

```java
C
CyC2018 已提交
436 437 438 439
public String frequencySort(String s) {
    Map<Character, Integer> frequencyForNum = new HashMap<>();
    for (char c : s.toCharArray())
        frequencyForNum.put(c, frequencyForNum.getOrDefault(c, 0) + 1);
C
CyC2018 已提交
440

C
CyC2018 已提交
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
    List<Character>[] frequencyBucket = new ArrayList[s.length() + 1];
    for (char c : frequencyForNum.keySet()) {
        int f = frequencyForNum.get(c);
        if (frequencyBucket[f] == null) {
            frequencyBucket[f] = new ArrayList<>();
        }
        frequencyBucket[f].add(c);
    }
    StringBuilder str = new StringBuilder();
    for (int i = frequencyBucket.length - 1; i >= 0; i--) {
        if (frequencyBucket[i] == null) {
            continue;
        }
        for (char c : frequencyBucket[i]) {
            for (int j = 0; j < i; j++) {
                str.append(c);
            }
        }
    }
    return str.toString();
C
CyC2018 已提交
461 462 463
}
```

C
CyC2018 已提交
464
### 荷兰国旗问题
C
CyC2018 已提交
465

C
CyC2018 已提交
466 467 468
荷兰国旗包含三种颜色:红、白、蓝。

有三种颜色的球,算法的目标是将这三种球按颜色顺序正确地排列。
C
CyC2018 已提交
469 470 471

它其实是三向切分快速排序的一种变种,在三向切分快速排序中,每次切分都将数组分成三个区间:小于切分元素、等于切分元素、大于切分元素,而该算法是将数组分成三个区间:等于红色、等于白色、等于蓝色。

C
CyC2018 已提交
472
<div align="center"> <img src="pics/3b49dd67-2c40-4b81-8ad2-7bbb1fe2fcbd.png"/> </div><br>
C
CyC2018 已提交
473

C
CyC2018 已提交
474
**按颜色进行排序** 
C
CyC2018 已提交
475

C
CyC2018 已提交
476
[75. Sort Colors (Medium)](https://leetcode.com/problems/sort-colors/description/)
C
CyC2018 已提交
477 478

```html
C
CyC2018 已提交
479 480
Input: [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
C
CyC2018 已提交
481 482
```

C
CyC2018 已提交
483
题目描述:只有 0/1/2 三种颜色。
C
CyC2018 已提交
484

C
CyC2018 已提交
485
```java
C
CyC2018 已提交
486 487 488 489 490 491 492 493 494 495 496
public void sortColors(int[] nums) {
    int zero = -1, one = 0, two = nums.length;
    while (one < two) {
        if (nums[one] == 0) {
            swap(nums, ++zero, one++);
        } else if (nums[one] == 2) {
            swap(nums, --two, one);
        } else {
            ++one;
        }
    }
C
CyC2018 已提交
497 498
}

C
CyC2018 已提交
499 500 501 502
private void swap(int[] nums, int i, int j) {
    int t = nums[i];
    nums[i] = nums[j];
    nums[j] = t;
C
CyC2018 已提交
503 504 505
}
```

C
CyC2018 已提交
506
## 贪心思想
C
CyC2018 已提交
507

C
CyC2018 已提交
508
保证每次操作都是局部最优的,并且最后得到的结果是全局最优的。
C
CyC2018 已提交
509

C
CyC2018 已提交
510
**分配饼干** 
C
CyC2018 已提交
511

C
CyC2018 已提交
512
[455. Assign Cookies (Easy)](https://leetcode.com/problems/assign-cookies/description/)
C
CyC2018 已提交
513

C
CyC2018 已提交
514
```html
C
CyC2018 已提交
515 516
Input: [1,2], [1,2,3]
Output: 2
C
CyC2018 已提交
517

C
CyC2018 已提交
518 519 520
Explanation: You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2.
You have 3 cookies and their sizes are big enough to gratify all of the children,
You need to output 2.
C
CyC2018 已提交
521
```
C
CyC2018 已提交
522

C
CyC2018 已提交
523
题目描述:每个孩子都有一个满足度,每个饼干都有一个大小,只有饼干的大小大于等于一个孩子的满足度,该孩子才会获得满足。求解最多可以获得满足的孩子数量。
C
CyC2018 已提交
524

C
CyC2018 已提交
525
给一个孩子的饼干应当尽量小又能满足该孩子,这样大饼干就能拿来给满足度比较大的孩子。因为最小的孩子最容易得到满足,所以先满足最小的孩子。
C
CyC2018 已提交
526

C
CyC2018 已提交
527
证明:假设在某次选择中,贪心策略选择给当前满足度最小的孩子分配第 m 个饼干,第 m 个饼干为可以满足该孩子的最小饼干。假设存在一种最优策略,给该孩子分配第 n 个饼干,并且 m < n。我们可以发现,经过这一轮分配,贪心策略分配后剩下的饼干一定有一个比最优策略来得大。因此在后续的分配中,贪心策略一定能满足更多的孩子。也就是说不存在比贪心策略更优的策略,即贪心策略就是最优策略。
C
CyC2018 已提交
528 529

```java
C
CyC2018 已提交
530 531 532 533 534 535 536 537 538 539 540
public int findContentChildren(int[] g, int[] s) {
    Arrays.sort(g);
    Arrays.sort(s);
    int gi = 0, si = 0;
    while (gi < g.length && si < s.length) {
        if (g[gi] <= s[si]) {
            gi++;
        }
        si++;
    }
    return gi;
C
CyC2018 已提交
541 542 543
}
```

C
CyC2018 已提交
544
**不重叠的区间个数** 
C
CyC2018 已提交
545

C
CyC2018 已提交
546
[435. Non-overlapping Intervals (Medium)](https://leetcode.com/problems/non-overlapping-intervals/description/)
C
CyC2018 已提交
547

C
CyC2018 已提交
548
```html
C
CyC2018 已提交
549
Input: [ [1,2], [1,2], [1,2] ]
C
CyC2018 已提交
550

C
CyC2018 已提交
551
Output: 2
C
CyC2018 已提交
552

C
CyC2018 已提交
553
Explanation: You need to remove two [1,2] to make the rest of intervals non-overlapping.
C
CyC2018 已提交
554 555
```

C
CyC2018 已提交
556
```html
C
CyC2018 已提交
557
Input: [ [1,2], [2,3] ]
C
CyC2018 已提交
558

C
CyC2018 已提交
559
Output: 0
C
CyC2018 已提交
560

C
CyC2018 已提交
561
Explanation: You don't need to remove any of the intervals since they're already non-overlapping.
C
CyC2018 已提交
562
```
C
CyC2018 已提交
563

C
CyC2018 已提交
564
题目描述:计算让一组区间不重叠所需要移除的区间个数。
C
CyC2018 已提交
565

C
CyC2018 已提交
566
先计算最多能组成的不重叠区间个数,然后用区间总个数减去不重叠区间的个数。
C
CyC2018 已提交
567

C
CyC2018 已提交
568
在每次选择中,区间的结尾最为重要,选择的区间结尾越小,留给后面的区间的空间越大,那么后面能够选择的区间个数也就越大。
C
CyC2018 已提交
569

C
CyC2018 已提交
570
按区间的结尾进行排序,每次选择结尾最小,并且和前一个区间不重叠的区间。
C
CyC2018 已提交
571 572

```java
C
CyC2018 已提交
573 574 575 576 577 578 579 580 581 582 583 584 585 586 587
public int eraseOverlapIntervals(Interval[] intervals) {
    if (intervals.length == 0) {
        return 0;
    }
    Arrays.sort(intervals, Comparator.comparingInt(o -> o.end));
    int cnt = 1;
    int end = intervals[0].end;
    for (int i = 1; i < intervals.length; i++) {
        if (intervals[i].start < end) {
            continue;
        }
        end = intervals[i].end;
        cnt++;
    }
    return intervals.length - cnt;
C
CyC2018 已提交
588 589 590
}
```

C
CyC2018 已提交
591
使用 lambda 表示式创建 Comparator 会导致算法运行时间过长,如果注重运行时间,可以修改为普通创建 Comparator 语句:
C
CyC2018 已提交
592 593

```java
C
CyC2018 已提交
594 595 596 597 598
Arrays.sort(intervals, new Comparator<Interval>() {
    @Override
    public int compare(Interval o1, Interval o2) {
        return o1.end - o2.end;
    }
C
CyC2018 已提交
599
});
C
CyC2018 已提交
600 601
```

C
CyC2018 已提交
602
**投飞镖刺破气球** 
C
CyC2018 已提交
603

C
CyC2018 已提交
604
[452. Minimum Number of Arrows to Burst Balloons (Medium)](https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/description/)
C
CyC2018 已提交
605 606

```
C
CyC2018 已提交
607
Input:
C
CyC2018 已提交
608
[[10,16], [2,8], [1,6], [7,12]]
C
CyC2018 已提交
609

C
CyC2018 已提交
610 611 612
Output:
2
```
C
CyC2018 已提交
613

C
CyC2018 已提交
614
题目描述:气球在一个水平数轴上摆放,可以重叠,飞镖垂直投向坐标轴,使得路径上的气球都会刺破。求解最小的投飞镖次数使所有气球都被刺破。
C
CyC2018 已提交
615

C
CyC2018 已提交
616
也是计算不重叠的区间个数,不过和 Non-overlapping Intervals 的区别在于,[1, 2] 和 [2, 3] 在本题中算是重叠区间。
C
CyC2018 已提交
617 618

```java
C
CyC2018 已提交
619 620 621 622 623 624 625 626 627 628 629 630 631 632
public int findMinArrowShots(int[][] points) {
    if (points.length == 0) {
        return 0;
    }
    Arrays.sort(points, Comparator.comparingInt(o -> o[1]));
    int cnt = 1, end = points[0][1];
    for (int i = 1; i < points.length; i++) {
        if (points[i][0] <= end) {
            continue;
        }
        cnt++;
        end = points[i][1];
    }
    return cnt;
C
CyC2018 已提交
633 634 635
}
```

C
CyC2018 已提交
636
**根据身高和序号重组队列** 
C
CyC2018 已提交
637

C
CyC2018 已提交
638
[406. Queue Reconstruction by Height(Medium)](https://leetcode.com/problems/queue-reconstruction-by-height/description/)
C
CyC2018 已提交
639

C
CyC2018 已提交
640 641
```html
Input:
C
CyC2018 已提交
642
[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]
C
CyC2018 已提交
643

C
CyC2018 已提交
644
Output:
C
CyC2018 已提交
645
[[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]
C
CyC2018 已提交
646
```
C
CyC2018 已提交
647

C
CyC2018 已提交
648
题目描述:一个学生用两个分量 (h, k) 描述,h 表示身高,k 表示排在前面的有 k 个学生的身高比他高或者和他一样高。
C
CyC2018 已提交
649

C
CyC2018 已提交
650
为了使插入操作不影响后续的操作,身高较高的学生应该先做插入操作,否则身高较小的学生原先正确插入的第 k 个位置可能会变成第 k+1 个位置。
C
CyC2018 已提交
651

C
CyC2018 已提交
652
身高降序、k 值升序,然后按排好序的顺序插入队列的第 k 个位置中。
C
CyC2018 已提交
653 654

```java
C
CyC2018 已提交
655 656 657 658 659 660 661 662 663 664
public int[][] reconstructQueue(int[][] people) {
    if (people == null || people.length == 0 || people[0].length == 0) {
        return new int[0][0];
    }
    Arrays.sort(people, (a, b) -> (a[0] == b[0] ? a[1] - b[1] : b[0] - a[0]));
    List<int[]> queue = new ArrayList<>();
    for (int[] p : people) {
        queue.add(p[1], p);
    }
    return queue.toArray(new int[queue.size()][]);
C
CyC2018 已提交
665 666 667
}
```

C
CyC2018 已提交
668
**分隔字符串使同种字符出现在一起** 
C
CyC2018 已提交
669

C
CyC2018 已提交
670
[763. Partition Labels (Medium)](https://leetcode.com/problems/partition-labels/description/)
C
CyC2018 已提交
671 672

```html
C
CyC2018 已提交
673 674
Input: S = "ababcbacadefegdehijhklij"
Output: [9,7,8]
C
CyC2018 已提交
675
Explanation:
C
CyC2018 已提交
676 677 678
The partition is "ababcbaca", "defegde", "hijhklij".
This is a partition so that each letter appears in at most one part.
A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits S into less parts.
C
CyC2018 已提交
679 680 681
```

```java
C
CyC2018 已提交
682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700
public List<Integer> partitionLabels(String S) {
    int[] lastIndexsOfChar = new int[26];
    for (int i = 0; i < S.length(); i++) {
        lastIndexsOfChar[char2Index(S.charAt(i))] = i;
    }
    List<Integer> partitions = new ArrayList<>();
    int firstIndex = 0;
    while (firstIndex < S.length()) {
        int lastIndex = firstIndex;
        for (int i = firstIndex; i < S.length() && i <= lastIndex; i++) {
            int index = lastIndexsOfChar[char2Index(S.charAt(i))];
            if (index > lastIndex) {
                lastIndex = index;
            }
        }
        partitions.add(lastIndex - firstIndex + 1);
        firstIndex = lastIndex + 1;
    }
    return partitions;
C
CyC2018 已提交
701 702
}

C
CyC2018 已提交
703 704
private int char2Index(char c) {
    return c - 'a';
C
CyC2018 已提交
705 706 707 708
}
```


C
CyC2018 已提交
709
**种植花朵** 
C
CyC2018 已提交
710

C
CyC2018 已提交
711
[605. Can Place Flowers (Easy)](https://leetcode.com/problems/can-place-flowers/description/)
C
CyC2018 已提交
712

C
CyC2018 已提交
713
```html
C
CyC2018 已提交
714 715
Input: flowerbed = [1,0,0,0,1], n = 1
Output: True
C
CyC2018 已提交
716 717
```

C
CyC2018 已提交
718
题目描述:花朵之间至少需要一个单位的间隔,求解是否能种下 n 朵花。
C
CyC2018 已提交
719

C
CyC2018 已提交
720
```java
C
CyC2018 已提交
721 722 723 724 725 726 727 728 729 730 731 732 733 734 735
public boolean canPlaceFlowers(int[] flowerbed, int n) {
    int len = flowerbed.length;
    int cnt = 0;
    for (int i = 0; i < len && cnt < n; i++) {
        if (flowerbed[i] == 1) {
            continue;
        }
        int pre = i == 0 ? 0 : flowerbed[i - 1];
        int next = i == len - 1 ? 0 : flowerbed[i + 1];
        if (pre == 0 && next == 0) {
            cnt++;
            flowerbed[i] = 1;
        }
    }
    return cnt >= n;
C
CyC2018 已提交
736 737 738
}
```

C
CyC2018 已提交
739
**判断是否为子序列** 
C
CyC2018 已提交
740

C
CyC2018 已提交
741
[392. Is Subsequence (Medium)](https://leetcode.com/problems/is-subsequence/description/)
C
CyC2018 已提交
742

C
CyC2018 已提交
743
```html
C
CyC2018 已提交
744 745
s = "abc", t = "ahbgdc"
Return true.
C
CyC2018 已提交
746
```
C
CyC2018 已提交
747

C
CyC2018 已提交
748
```java
C
CyC2018 已提交
749 750 751 752 753 754 755 756 757
public boolean isSubsequence(String s, String t) {
    int index = -1;
    for (char c : s.toCharArray()) {
        index = t.indexOf(c, index + 1);
        if (index == -1) {
            return false;
        }
    }
    return true;
C
CyC2018 已提交
758 759
}
```
C
CyC2018 已提交
760

C
CyC2018 已提交
761
**修改一个数成为非递减数组** 
C
CyC2018 已提交
762

C
CyC2018 已提交
763
[665. Non-decreasing Array (Easy)](https://leetcode.com/problems/non-decreasing-array/description/)
C
CyC2018 已提交
764

C
CyC2018 已提交
765
```html
C
CyC2018 已提交
766 767 768
Input: [4,2,3]
Output: True
Explanation: You could modify the first 4 to 1 to get a non-decreasing array.
C
CyC2018 已提交
769
```
C
CyC2018 已提交
770

C
CyC2018 已提交
771
题目描述:判断一个数组能不能只修改一个数就成为非递减数组。
C
CyC2018 已提交
772

C
CyC2018 已提交
773
在出现 nums[i] < nums[i - 1] 时,需要考虑的是应该修改数组的哪个数,使得本次修改能使 i 之前的数组成为非递减数组,并且  **不影响后续的操作** 。优先考虑令 nums[i - 1] = nums[i],因为如果修改 nums[i] = nums[i - 1] 的话,那么 nums[i] 这个数会变大,就有可能比 nums[i + 1] 大,从而影响了后续操作。还有一个比较特别的情况就是 nums[i] < nums[i - 2],只修改 nums[i - 1] = nums[i] 不能使数组成为非递减数组,只能修改 nums[i] = nums[i - 1]。
C
CyC2018 已提交
774

C
CyC2018 已提交
775
```java
C
CyC2018 已提交
776 777 778 779 780 781 782 783 784 785 786 787 788 789
public boolean checkPossibility(int[] nums) {
    int cnt = 0;
    for (int i = 1; i < nums.length && cnt < 2; i++) {
        if (nums[i] >= nums[i - 1]) {
            continue;
        }
        cnt++;
        if (i - 2 >= 0 && nums[i - 2] > nums[i]) {
            nums[i] = nums[i - 1];
        } else {
            nums[i - 1] = nums[i];
        }
    }
    return cnt <= 1;
C
CyC2018 已提交
790 791
}
```
C
CyC2018 已提交
792

C
CyC2018 已提交
793
**股票的最大收益** 
C
CyC2018 已提交
794

C
CyC2018 已提交
795
[122. Best Time to Buy and Sell Stock II (Easy)](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/description/)
C
CyC2018 已提交
796

C
CyC2018 已提交
797
题目描述:一次股票交易包含买入和卖出,多个交易之间不能交叉进行。
C
CyC2018 已提交
798

C
CyC2018 已提交
799
对于 [a, b, c, d],如果有 a <= b <= c <= d 那么最大收益为 d - a d - a = (d - c) + (c - b) + (b - a) 因此当访问到一个 prices[i]  prices[i] - prices[i-1] > 0,那么就把 prices[i] - prices[i-1] 添加到收益中,从而在局部最优的情况下也保证全局最优。
C
CyC2018 已提交
800

C
CyC2018 已提交
801
```java
C
CyC2018 已提交
802 803 804 805 806 807 808 809
public int maxProfit(int[] prices) {
    int profit = 0;
    for (int i = 1; i < prices.length; i++) {
        if (prices[i] > prices[i - 1]) {
            profit += (prices[i] - prices[i - 1]);
        }
    }
    return profit;
C
CyC2018 已提交
810
}
C
CyC2018 已提交
811 812
```

C
CyC2018 已提交
813
**子数组最大的和** 
C
CyC2018 已提交
814

C
CyC2018 已提交
815
[53. Maximum Subarray (Easy)](https://leetcode.com/problems/maximum-subarray/description/)
C
CyC2018 已提交
816 817

```html
C
CyC2018 已提交
818 819
For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
the contiguous subarray [4,-1,2,1] has the largest sum = 6.
C
CyC2018 已提交
820 821 822
```

```java
C
CyC2018 已提交
823 824 825 826 827 828 829 830 831 832 833
public int maxSubArray(int[] nums) {
    if (nums == null || nums.length == 0) {
        return 0;
    }
    int preSum = nums[0];
    int maxSum = preSum;
    for (int i = 1; i < nums.length; i++) {
        preSum = preSum > 0 ? preSum + nums[i] : nums[i];
        maxSum = Math.max(maxSum, preSum);
    }
    return maxSum;
C
CyC2018 已提交
834 835 836
}
```

C
CyC2018 已提交
837
**买入和售出股票最大的收益** 
C
CyC2018 已提交
838

C
CyC2018 已提交
839
[121. Best Time to Buy and Sell Stock (Easy)](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/)
C
CyC2018 已提交
840 841 842 843 844 845

题目描述:只进行一次交易。

只要记录前面的最小价格,将这个最小价格作为买入价格,然后将当前的价格作为售出价格,查看当前收益是不是最大收益。

```java
C
CyC2018 已提交
846 847 848 849 850 851 852 853 854 855
public int maxProfit(int[] prices) {
    int n = prices.length;
    if (n == 0) return 0;
    int soFarMin = prices[0];
    int max = 0;
    for (int i = 1; i < n; i++) {
        if (soFarMin > prices[i]) soFarMin = prices[i];
        else max = Math.max(max, prices[i] - soFarMin);
    }
    return max;
C
CyC2018 已提交
856 857 858
}
```

C
CyC2018 已提交
859
## 二分查找
C
CyC2018 已提交
860

C
CyC2018 已提交
861
**正常实现** 
C
CyC2018 已提交
862

C
CyC2018 已提交
863
```java
C
CyC2018 已提交
864 865 866 867 868 869 870 871 872 873 874 875 876
public int binarySearch(int[] nums, int key) {
    int l = 0, h = nums.length - 1;
    while (l <= h) {
        int m = l + (h - l) / 2;
        if (nums[m] == key) {
            return m;
        } else if (nums[m] > key) {
            h = m - 1;
        } else {
            l = m + 1;
        }
    }
    return -1;
C
CyC2018 已提交
877
}
C
CyC2018 已提交
878 879
```

C
CyC2018 已提交
880
**时间复杂度** 
C
CyC2018 已提交
881

C
CyC2018 已提交
882
二分查找也称为折半查找,每次都能将查找区间减半,这种折半特性的算法时间复杂度为 O(logN)。
C
CyC2018 已提交
883

C
CyC2018 已提交
884
**m 计算** 
C
CyC2018 已提交
885

C
CyC2018 已提交
886
有两种计算中值 m 的方式:
C
CyC2018 已提交
887

C
CyC2018 已提交
888 889
- m = (l + h) / 2
- m = l + (h - l) / 2
C
CyC2018 已提交
890

C
CyC2018 已提交
891
l + h 可能出现加法溢出,最好使用第二种方式。
C
CyC2018 已提交
892

C
CyC2018 已提交
893
**返回值** 
C
CyC2018 已提交
894

C
CyC2018 已提交
895
循环退出时如果仍然没有查找到 key,那么表示查找失败。可以有两种返回值:
C
CyC2018 已提交
896

C
CyC2018 已提交
897 898
- -1:以一个错误码表示没有查找到 key
- l:将 key 插入到 nums 中的正确位置
C
CyC2018 已提交
899

C
CyC2018 已提交
900
**变种** 
C
CyC2018 已提交
901

C
CyC2018 已提交
902
二分查找可以有很多变种,变种实现要注意边界值的判断。例如在一个有重复元素的数组中查找 key 的最左位置的实现如下:
C
CyC2018 已提交
903 904

```java
C
CyC2018 已提交
905 906 907 908 909 910 911 912 913 914 915
public int binarySearch(int[] nums, int key) {
    int l = 0, h = nums.length - 1;
    while (l < h) {
        int m = l + (h - l) / 2;
        if (nums[m] >= key) {
            h = m;
        } else {
            l = m + 1;
        }
    }
    return l;
C
CyC2018 已提交
916
}
C
CyC2018 已提交
917
```
C
CyC2018 已提交
918

C
CyC2018 已提交
919 920
该实现和正常实现有以下不同:

C
CyC2018 已提交
921 922 923
- 循环条件为 l < h
- h 的赋值表达式为 h = m
- 最后返回 l 而不是 -1
C
CyC2018 已提交
924

C
CyC2018 已提交
925
在 nums[m] >= key 的情况下,可以推导出最左 key 位于 [l, m] 区间中,这是一个闭区间。h 的赋值表达式为 h = m,因为 m 位置也可能是解。
C
CyC2018 已提交
926

C
CyC2018 已提交
927
在 h 的赋值表达式为 h = mid 的情况下,如果循环条件为 l <= h,那么会出现循环无法退出的情况,因此循环条件只能是 l < h。以下演示了循环条件为 l <= h 时循环无法退出的情况:
C
CyC2018 已提交
928 929

```text
C
CyC2018 已提交
930 931 932 933 934 935
nums = {0, 1, 2}, key = 1
l   m   h
0   1   2  nums[m] >= key
0   0   1  nums[m] < key
1   1   1  nums[m] >= key
1   1   1  nums[m] >= key
C
CyC2018 已提交
936 937 938
...
```

C
CyC2018 已提交
939
当循环体退出时,不表示没有查找到 key,因此最后返回的结果不应该为 -1。为了验证有没有查找到,需要在调用端判断一下返回位置上的值和 key 是否相等。
C
CyC2018 已提交
940

C
CyC2018 已提交
941
**求开方** 
C
CyC2018 已提交
942

C
CyC2018 已提交
943
[69. Sqrt(x) (Easy)](https://leetcode.com/problems/sqrtx/description/)
C
CyC2018 已提交
944 945

```html
C
CyC2018 已提交
946 947
Input: 4
Output: 2
C
CyC2018 已提交
948

C
CyC2018 已提交
949 950 951
Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since we want to return an integer, the decimal part will be truncated.
C
CyC2018 已提交
952 953
```

C
CyC2018 已提交
954
一个数 x 的开方 sqrt 一定在 0 \~ x 之间,并且满足 sqrt == x / sqrt。可以利用二分查找在 0 \~ x 之间查找 sqrt。
C
CyC2018 已提交
955

C
CyC2018 已提交
956
对于 x = 8,它的开方是 2.82842...,最后应该返回 2 而不是 3。在循环条件为 l <= h 并且循环退出时,h 总是比 l 小 1,也就是说 h = 2,l = 3,因此最后的返回值应该为 h 而不是 l。
C
CyC2018 已提交
957 958

```java
C
CyC2018 已提交
959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975
public int mySqrt(int x) {
    if (x <= 1) {
        return x;
    }
    int l = 1, h = x;
    while (l <= h) {
        int mid = l + (h - l) / 2;
        int sqrt = x / mid;
        if (sqrt == mid) {
            return mid;
        } else if (mid > sqrt) {
            h = mid - 1;
        } else {
            l = mid + 1;
        }
    }
    return h;
C
CyC2018 已提交
976 977 978
}
```

C
CyC2018 已提交
979
**大于给定元素的最小元素** 
C
CyC2018 已提交
980

C
CyC2018 已提交
981
[744. Find Smallest Letter Greater Than Target (Easy)](https://leetcode.com/problems/find-smallest-letter-greater-than-target/description/)
C
CyC2018 已提交
982 983 984

```html
Input:
C
CyC2018 已提交
985 986 987
letters = ["c", "f", "j"]
target = "d"
Output: "f"
C
CyC2018 已提交
988 989

Input:
C
CyC2018 已提交
990 991 992
letters = ["c", "f", "j"]
target = "k"
Output: "c"
C
CyC2018 已提交
993 994
```

C
CyC2018 已提交
995
题目描述:给定一个有序的字符数组 letters 和一个字符 target,要求找出 letters 中大于 target 的最小字符,如果找不到就返回第 1 个字符。
C
CyC2018 已提交
996 997

```java
C
CyC2018 已提交
998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009
public char nextGreatestLetter(char[] letters, char target) {
    int n = letters.length;
    int l = 0, h = n - 1;
    while (l <= h) {
        int m = l + (h - l) / 2;
        if (letters[m] <= target) {
            l = m + 1;
        } else {
            h = m - 1;
        }
    }
    return l < n ? letters[l] : letters[0];
C
CyC2018 已提交
1010 1011 1012
}
```

C
CyC2018 已提交
1013
**有序数组的 Single Element** 
C
CyC2018 已提交
1014

C
CyC2018 已提交
1015
[540. Single Element in a Sorted Array (Medium)](https://leetcode.com/problems/single-element-in-a-sorted-array/description/)
C
CyC2018 已提交
1016 1017

```html
C
CyC2018 已提交
1018 1019
Input: [1, 1, 2, 3, 3, 4, 4, 8, 8]
Output: 2
C
CyC2018 已提交
1020 1021
```

C
CyC2018 已提交
1022
题目描述:一个有序数组只有一个数不出现两次,找出这个数。要求以 O(logN) 时间复杂度进行求解。
C
CyC2018 已提交
1023

C
CyC2018 已提交
1024
令 index 为 Single Element 在数组中的位置。如果 m 为偶数,并且 m + 1 < index那么 nums[m] == nums[m + 1];m + 1 >= index,那么 nums[m] != nums[m + 1]。
C
CyC2018 已提交
1025

C
CyC2018 已提交
1026
从上面的规律可以知道,如果 nums[m] == nums[m + 1],那么 index 所在的数组位置为 [m + 2, h],此时令 l = m + 2;如果 nums[m] != nums[m + 1],那么 index 所在的数组位置为 [l, m],此时令 h = m。
C
CyC2018 已提交
1027

C
CyC2018 已提交
1028
因为 h 的赋值表达式为 h = m,那么循环条件也就只能使用 l < h 这种形式。
C
CyC2018 已提交
1029 1030

```java
C
CyC2018 已提交
1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
public int singleNonDuplicate(int[] nums) {
    int l = 0, h = nums.length - 1;
    while (l < h) {
        int m = l + (h - l) / 2;
        if (m % 2 == 1) {
            m--;   // 保证 l/h/m 都在偶数位,使得查找区间大小一直都是奇数
        }
        if (nums[m] == nums[m + 1]) {
            l = m + 2;
        } else {
            h = m;
        }
    }
    return nums[l];
C
CyC2018 已提交
1045 1046 1047
}
```

C
CyC2018 已提交
1048
**第一个错误的版本** 
C
CyC2018 已提交
1049

C
CyC2018 已提交
1050
[278. First Bad Version (Easy)](https://leetcode.com/problems/first-bad-version/description/)
C
CyC2018 已提交
1051

C
CyC2018 已提交
1052
题目描述:给定一个元素 n 代表有 [1, 2, ..., n] 版本,可以调用 isBadVersion(int x) 知道某个版本是否错误,要求找到第一个错误的版本。
C
CyC2018 已提交
1053

C
CyC2018 已提交
1054
如果第 m 个版本出错,则表示第一个错误的版本在 [l, m] 之间,令 h = m;否则第一个错误的版本在 [m + 1, h] 之间,令 l = m + 1。
C
CyC2018 已提交
1055

C
CyC2018 已提交
1056
因为 h 的赋值表达式为 h = m,因此循环条件为 l < h。
C
CyC2018 已提交
1057 1058

```java
C
CyC2018 已提交
1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069
public int firstBadVersion(int n) {
    int l = 1, h = n;
    while (l < h) {
        int mid = l + (h - l) / 2;
        if (isBadVersion(mid)) {
            h = mid;
        } else {
            l = mid + 1;
        }
    }
    return l;
C
CyC2018 已提交
1070 1071 1072
}
```

C
CyC2018 已提交
1073
**旋转数组的最小数字** 
C
CyC2018 已提交
1074

C
CyC2018 已提交
1075
[153. Find Minimum in Rotated Sorted Array (Medium)](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/description/)
C
CyC2018 已提交
1076 1077

```html
C
CyC2018 已提交
1078 1079
Input: [3,4,5,1,2],
Output: 1
C
CyC2018 已提交
1080 1081 1082
```

```java
C
CyC2018 已提交
1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093
public int findMin(int[] nums) {
    int l = 0, h = nums.length - 1;
    while (l < h) {
        int m = l + (h - l) / 2;
        if (nums[m] <= nums[h]) {
            h = m;
        } else {
            l = m + 1;
        }
    }
    return nums[l];
C
CyC2018 已提交
1094 1095 1096
}
```

C
CyC2018 已提交
1097
**查找区间** 
C
CyC2018 已提交
1098

C
CyC2018 已提交
1099
[34. Search for a Range (Medium)](https://leetcode.com/problems/search-for-a-range/description/)
C
CyC2018 已提交
1100 1101

```html
C
CyC2018 已提交
1102 1103
Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]
C
CyC2018 已提交
1104

C
CyC2018 已提交
1105 1106
Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]
C
CyC2018 已提交
1107 1108 1109
```

```java
C
CyC2018 已提交
1110 1111 1112 1113 1114 1115 1116 1117
public int[] searchRange(int[] nums, int target) {
    int first = binarySearch(nums, target);
    int last = binarySearch(nums, target + 1) - 1;
    if (first == nums.length || nums[first] != target) {
        return new int[]{-1, -1};
    } else {
        return new int[]{first, Math.max(first, last)};
    }
C
CyC2018 已提交
1118 1119
}

C
CyC2018 已提交
1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130
private int binarySearch(int[] nums, int target) {
    int l = 0, h = nums.length; // 注意 h 的初始值
    while (l < h) {
        int m = l + (h - l) / 2;
        if (nums[m] >= target) {
            h = m;
        } else {
            l = m + 1;
        }
    }
    return l;
C
CyC2018 已提交
1131 1132 1133
}
```

C
CyC2018 已提交
1134
## 分治
C
CyC2018 已提交
1135

C
CyC2018 已提交
1136
**给表达式加括号** 
C
CyC2018 已提交
1137

C
CyC2018 已提交
1138
[241. Different Ways to Add Parentheses (Medium)](https://leetcode.com/problems/different-ways-to-add-parentheses/description/)
C
CyC2018 已提交
1139 1140

```html
C
CyC2018 已提交
1141
Input: "2-1-1".
C
CyC2018 已提交
1142

C
CyC2018 已提交
1143 1144
((2-1)-1) = 0
(2-(1-1)) = 2
C
CyC2018 已提交
1145

C
CyC2018 已提交
1146
Output : [0, 2]
C
CyC2018 已提交
1147 1148 1149
```

```java
C
CyC2018 已提交
1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177
public List<Integer> diffWaysToCompute(String input) {
    List<Integer> ways = new ArrayList<>();
    for (int i = 0; i < input.length(); i++) {
        char c = input.charAt(i);
        if (c == '+' || c == '-' || c == '*') {
            List<Integer> left = diffWaysToCompute(input.substring(0, i));
            List<Integer> right = diffWaysToCompute(input.substring(i + 1));
            for (int l : left) {
                for (int r : right) {
                    switch (c) {
                        case '+':
                            ways.add(l + r);
                            break;
                        case '-':
                            ways.add(l - r);
                            break;
                        case '*':
                            ways.add(l * r);
                            break;
                    }
                }
            }
        }
    }
    if (ways.size() == 0) {
        ways.add(Integer.valueOf(input));
    }
    return ways;
C
CyC2018 已提交
1178 1179 1180
}
```

C
CyC2018 已提交
1181
## 搜索
C
CyC2018 已提交
1182 1183 1184

深度优先搜索和广度优先搜索广泛运用于树和图中,但是它们的应用远远不止如此。

C
CyC2018 已提交
1185
### BFS
C
CyC2018 已提交
1186

C
CyC2018 已提交
1187
<div align="center"> <img src="pics/4ff355cf-9a7f-4468-af43-e5b02038facc.jpg"/> </div><br>
C
CyC2018 已提交
1188

C
CyC2018 已提交
1189
广度优先搜索一层一层地进行遍历,每层遍历都以上一层遍历的结果作为起点,遍历一个距离能访问到的所有节点。需要注意的是,遍历过的节点不能再次被遍历。
C
CyC2018 已提交
1190 1191 1192

第一层:

C
CyC2018 已提交
1193
- 0 -> {6,2,1,5}
C
CyC2018 已提交
1194 1195 1196

第二层:

C
CyC2018 已提交
1197 1198 1199 1200
- 6 -> {4}
- 2 -> {}
- 1 -> {}
- 5 -> {3}
C
CyC2018 已提交
1201 1202 1203

第三层:

C
CyC2018 已提交
1204 1205
- 4 -> {}
- 3 -> {}
C
CyC2018 已提交
1206

C
CyC2018 已提交
1207
每一层遍历的节点都与根节点距离相同。设 d<sub>i</sub> 表示第 i 个节点与根节点的距离,推导出一个结论:对于先遍历的节点 i 与后遍历的节点 j,有 d<sub>i</sub> <= d<sub>j</sub>。利用这个结论,可以求解最短路径等  **最优解**  问题:第一次遍历到目的节点,其所经过的路径为最短路径。应该注意的是,使用 BFS 只能求解无权图的最短路径。
C
CyC2018 已提交
1208

C
CyC2018 已提交
1209
在程序实现 BFS 时需要考虑以下问题:
C
CyC2018 已提交
1210

C
CyC2018 已提交
1211 1212
- 队列:用来存储每一轮遍历得到的节点;
- 标记:对于遍历过的节点,应该将它标记,防止重复遍历。
C
CyC2018 已提交
1213

C
CyC2018 已提交
1214
**计算在网格中从原点到特定点的最短路径长度** 
C
CyC2018 已提交
1215 1216 1217

```html
[[1,1,0,1],
C
CyC2018 已提交
1218 1219 1220
 [1,0,1,0],
 [1,1,1,1],
 [1,0,1,1]]
C
CyC2018 已提交
1221 1222
```

C
CyC2018 已提交
1223
1 表示可以经过某个位置,求解从 (0, 0) 位置到 (tr, tc) 位置的最短路径长度。
C
CyC2018 已提交
1224 1225

```java
C
CyC2018 已提交
1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251
public int minPathLength(int[][] grids, int tr, int tc) {
    final int[][] direction = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
    final int m = grids.length, n = grids[0].length;
    Queue<Pair<Integer, Integer>> queue = new LinkedList<>();
    queue.add(new Pair<>(0, 0));
    int pathLength = 0;
    while (!queue.isEmpty()) {
        int size = queue.size();
        pathLength++;
        while (size-- > 0) {
            Pair<Integer, Integer> cur = queue.poll();
            int cr = cur.getKey(), cc = cur.getValue();
            grids[cr][cc] = 0; // 标记
            for (int[] d : direction) {
                int nr = cr + d[0], nc = cc + d[1];
                if (nr < 0 || nr >= m || nc < 0 || nc >= n || grids[nr][nc] == 0) {
                    continue;
                }
                if (nr == tr && nc == tc) {
                    return pathLength;
                }
                queue.add(new Pair<>(nr, nc));
            }
        }
    }
    return -1;
C
CyC2018 已提交
1252 1253 1254
}
```

C
CyC2018 已提交
1255
**组成整数的最小平方数数量** 
C
CyC2018 已提交
1256

C
CyC2018 已提交
1257
[279. Perfect Squares (Medium)](https://leetcode.com/problems/perfect-squares/description/)
C
CyC2018 已提交
1258 1259

```html
C
CyC2018 已提交
1260
For example, given n = 12, return 3 because 12 = 4 + 4 + 4; given n = 13, return 2 because 13 = 4 + 9.
C
CyC2018 已提交
1261 1262 1263 1264
```

可以将每个整数看成图中的一个节点,如果两个整数之差为一个平方数,那么这两个整数所在的节点就有一条边。

C
CyC2018 已提交
1265
要求解最小的平方数数量,就是求解从节点 n 到节点 0 的最短路径。
C
CyC2018 已提交
1266 1267 1268 1269

本题也可以用动态规划求解,在之后动态规划部分中会再次出现。

```java
C
CyC2018 已提交
1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298
public int numSquares(int n) {
    List<Integer> squares = generateSquares(n);
    Queue<Integer> queue = new LinkedList<>();
    boolean[] marked = new boolean[n + 1];
    queue.add(n);
    marked[n] = true;
    int level = 0;
    while (!queue.isEmpty()) {
        int size = queue.size();
        level++;
        while (size-- > 0) {
            int cur = queue.poll();
            for (int s : squares) {
                int next = cur - s;
                if (next < 0) {
                    break;
                }
                if (next == 0) {
                    return level;
                }
                if (marked[next]) {
                    continue;
                }
                marked[next] = true;
                queue.add(next);
            }
        }
    }
    return n;
C
CyC2018 已提交
1299 1300 1301
}

/**
C
CyC2018 已提交
1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314
 * 生成小于 n 的平方数序列
 * @return 1,4,9,...
 */
private List<Integer> generateSquares(int n) {
    List<Integer> squares = new ArrayList<>();
    int square = 1;
    int diff = 3;
    while (square <= n) {
        squares.add(square);
        square += diff;
        diff += 2;
    }
    return squares;
C
CyC2018 已提交
1315 1316 1317
}
```

C
CyC2018 已提交
1318
**最短单词路径** 
C
CyC2018 已提交
1319

C
CyC2018 已提交
1320
[127. Word Ladder (Medium)](https://leetcode.com/problems/word-ladder/description/)
C
CyC2018 已提交
1321 1322 1323

```html
Input:
C
CyC2018 已提交
1324 1325 1326
beginWord = "hit",
endWord = "cog",
wordList = ["hot","dot","dog","lot","log","cog"]
C
CyC2018 已提交
1327

C
CyC2018 已提交
1328
Output: 5
C
CyC2018 已提交
1329

C
CyC2018 已提交
1330 1331
Explanation: As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length 5.
C
CyC2018 已提交
1332 1333 1334 1335
```

```html
Input:
C
CyC2018 已提交
1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log"]

Output: 0

Explanation: The endWord "cog" is not in wordList, therefore no possible transformation.
```

题目描述:找出一条从 beginWord 到 endWord 的最短路径,每次移动规定为改变一个字符,并且改变之后的字符串必须在 wordList 中。

```java
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
    wordList.add(beginWord);
    int N = wordList.size();
    int start = N - 1;
    int end = 0;
    while (end < N && !wordList.get(end).equals(endWord)) {
        end++;
    }
    if (end == N) {
        return 0;
    }
    List<Integer>[] graphic = buildGraphic(wordList);
    return getShortestPath(graphic, start, end);
}

private List<Integer>[] buildGraphic(List<String> wordList) {
    int N = wordList.size();
    List<Integer>[] graphic = new List[N];
    for (int i = 0; i < N; i++) {
        graphic[i] = new ArrayList<>();
        for (int j = 0; j < N; j++) {
            if (isConnect(wordList.get(i), wordList.get(j))) {
                graphic[i].add(j);
            }
        }
    }
    return graphic;
}

private boolean isConnect(String s1, String s2) {
    int diffCnt = 0;
    for (int i = 0; i < s1.length() && diffCnt <= 1; i++) {
        if (s1.charAt(i) != s2.charAt(i)) {
            diffCnt++;
        }
    }
    return diffCnt == 1;
}

private int getShortestPath(List<Integer>[] graphic, int start, int end) {
    Queue<Integer> queue = new LinkedList<>();
    boolean[] marked = new boolean[graphic.length];
    queue.add(start);
    marked[start] = true;
    int path = 1;
    while (!queue.isEmpty()) {
        int size = queue.size();
        path++;
        while (size-- > 0) {
            int cur = queue.poll();
            for (int next : graphic[cur]) {
                if (next == end) {
                    return path;
                }
                if (marked[next]) {
                    continue;
                }
                marked[next] = true;
                queue.add(next);
            }
        }
    }
    return 0;
}
```

### DFS

<div align="center"> <img src="pics/f7f7e3e5-7dd4-4173-9999-576b9e2ac0a2.png"/> </div><br>
C
CyC2018 已提交
1417

C
CyC2018 已提交
1418
广度优先搜索一层一层遍历,每一层得到的所有新节点,要用队列存储起来以备下一层遍历的时候再遍历。
C
CyC2018 已提交
1419

C
CyC2018 已提交
1420
而深度优先搜索在得到一个新节点时立即对新节点进行遍历:从节点 0 出发开始遍历,得到到新节点 6 时,立马对新节点 6 进行遍历,得到新节点 4;如此反复以这种方式遍历新节点,直到没有新节点了,此时返回。返回到根节点 0 的情况是,继续对根节点 0 进行遍历,得到新节点 2,然后继续以上步骤。
C
CyC2018 已提交
1421

C
CyC2018 已提交
1422
从一个节点出发,使用 DFS 对一个图进行遍历时,能够遍历到的节点都是从初始节点可达的,DFS 常用来求解这种  **可达性**  问题。
C
CyC2018 已提交
1423

C
CyC2018 已提交
1424
在程序实现 DFS 时需要考虑以下问题:
C
CyC2018 已提交
1425

C
CyC2018 已提交
1426 1427
- 栈:用栈来保存当前节点信息,当遍历新节点返回时能够继续遍历当前节点。可以使用递归栈。
- 标记:和 BFS 一样同样需要对已经遍历过的节点进行标记。
C
CyC2018 已提交
1428

C
CyC2018 已提交
1429
**查找最大的连通面积** 
C
CyC2018 已提交
1430

C
CyC2018 已提交
1431
[695. Max Area of Island (Easy)](https://leetcode.com/problems/max-area-of-island/description/)
C
CyC2018 已提交
1432 1433 1434

```html
[[0,0,1,0,0,0,0,1,0,0,0,0,0],
C
CyC2018 已提交
1435 1436 1437 1438 1439 1440 1441
 [0,0,0,0,0,0,0,1,1,1,0,0,0],
 [0,1,1,0,1,0,0,0,0,0,0,0,0],
 [0,1,0,0,1,1,0,0,1,0,1,0,0],
 [0,1,0,0,1,1,0,0,1,1,1,0,0],
 [0,0,0,0,0,0,0,0,0,0,1,0,0],
 [0,0,0,0,0,0,0,1,1,1,0,0,0],
 [0,0,0,0,0,0,0,1,1,0,0,0,0]]
C
CyC2018 已提交
1442 1443 1444
```

```java
C
CyC2018 已提交
1445 1446
private int m, n;
private int[][] direction = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
C
CyC2018 已提交
1447

C
CyC2018 已提交
1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460
public int maxAreaOfIsland(int[][] grid) {
    if (grid == null || grid.length == 0) {
        return 0;
    }
    m = grid.length;
    n = grid[0].length;
    int maxArea = 0;
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            maxArea = Math.max(maxArea, dfs(grid, i, j));
        }
    }
    return maxArea;
C
CyC2018 已提交
1461 1462
}

C
CyC2018 已提交
1463 1464 1465 1466 1467 1468 1469 1470 1471 1472
private int dfs(int[][] grid, int r, int c) {
    if (r < 0 || r >= m || c < 0 || c >= n || grid[r][c] == 0) {
        return 0;
    }
    grid[r][c] = 0;
    int area = 1;
    for (int[] d : direction) {
        area += dfs(grid, r + d[0], c + d[1]);
    }
    return area;
C
CyC2018 已提交
1473 1474 1475
}
```

C
CyC2018 已提交
1476
**矩阵中的连通分量数目** 
C
CyC2018 已提交
1477

C
CyC2018 已提交
1478
[200. Number of Islands (Medium)](https://leetcode.com/problems/number-of-islands/description/)
C
CyC2018 已提交
1479 1480

```html
C
CyC2018 已提交
1481
Input:
C
CyC2018 已提交
1482
11000
C
CyC2018 已提交
1483 1484 1485 1486
11000
00100
00011

C
CyC2018 已提交
1487
Output: 3
C
CyC2018 已提交
1488 1489
```

C
CyC2018 已提交
1490 1491
可以将矩阵表示看成一张有向图。

C
CyC2018 已提交
1492
```java
C
CyC2018 已提交
1493 1494
private int m, n;
private int[][] direction = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
C
CyC2018 已提交
1495

C
CyC2018 已提交
1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511
public int numIslands(char[][] grid) {
    if (grid == null || grid.length == 0) {
        return 0;
    }
    m = grid.length;
    n = grid[0].length;
    int islandsNum = 0;
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            if (grid[i][j] != '0') {
                dfs(grid, i, j);
                islandsNum++;
            }
        }
    }
    return islandsNum;
C
CyC2018 已提交
1512 1513
}

C
CyC2018 已提交
1514 1515 1516 1517 1518 1519 1520 1521
private void dfs(char[][] grid, int i, int j) {
    if (i < 0 || i >= m || j < 0 || j >= n || grid[i][j] == '0') {
        return;
    }
    grid[i][j] = '0';
    for (int[] d : direction) {
        dfs(grid, i + d[0], j + d[1]);
    }
C
CyC2018 已提交
1522 1523 1524
}
```

C
CyC2018 已提交
1525
**好友关系的连通分量数目** 
C
CyC2018 已提交
1526

C
CyC2018 已提交
1527
[547. Friend Circles (Medium)](https://leetcode.com/problems/friend-circles/description/)
C
CyC2018 已提交
1528 1529

```html
C
CyC2018 已提交
1530 1531
Input:
[[1,1,0],
C
CyC2018 已提交
1532 1533
 [1,1,0],
 [0,0,1]]
C
CyC2018 已提交
1534

C
CyC2018 已提交
1535
Output: 2
C
CyC2018 已提交
1536

C
CyC2018 已提交
1537 1538
Explanation:The 0th and 1st students are direct friends, so they are in a friend circle.
The 2nd student himself is in a friend circle. So return 2.
C
CyC2018 已提交
1539 1540
```

C
CyC2018 已提交
1541
题目描述:好友关系可以看成是一个无向图,例如第 0 个人与第 1 个人是好友,那么 M[0][1] 和 M[1][0] 的值都为 1。
C
CyC2018 已提交
1542 1543

```java
C
CyC2018 已提交
1544
private int n;
C
CyC2018 已提交
1545

C
CyC2018 已提交
1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556
public int findCircleNum(int[][] M) {
    n = M.length;
    int circleNum = 0;
    boolean[] hasVisited = new boolean[n];
    for (int i = 0; i < n; i++) {
        if (!hasVisited[i]) {
            dfs(M, i, hasVisited);
            circleNum++;
        }
    }
    return circleNum;
C
CyC2018 已提交
1557 1558
}

C
CyC2018 已提交
1559 1560 1561 1562 1563 1564 1565
private void dfs(int[][] M, int i, boolean[] hasVisited) {
    hasVisited[i] = true;
    for (int k = 0; k < n; k++) {
        if (M[i][k] == 1 && !hasVisited[k]) {
            dfs(M, k, hasVisited);
        }
    }
C
CyC2018 已提交
1566 1567 1568
}
```

C
CyC2018 已提交
1569
**填充封闭区域** 
C
CyC2018 已提交
1570

C
CyC2018 已提交
1571
[130. Surrounded Regions (Medium)](https://leetcode.com/problems/surrounded-regions/description/)
C
CyC2018 已提交
1572 1573

```html
C
CyC2018 已提交
1574 1575 1576 1577 1578
For example,
X X X X
X O O X
X X O X
X O X X
C
CyC2018 已提交
1579

C
CyC2018 已提交
1580 1581 1582 1583 1584
After running your function, the board should be:
X X X X
X X X X
X X X X
X O X X
C
CyC2018 已提交
1585 1586
```

C
CyC2018 已提交
1587
题目描述:使被 'X' 包围的 'O' 转换为 'X'。
C
CyC2018 已提交
1588 1589 1590 1591

先填充最外侧,剩下的就是里侧了。

```java
C
CyC2018 已提交
1592 1593
private int[][] direction = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
private int m, n;
C
CyC2018 已提交
1594

C
CyC2018 已提交
1595 1596 1597 1598
public void solve(char[][] board) {
    if (board == null || board.length == 0) {
        return;
    }
C
CyC2018 已提交
1599

C
CyC2018 已提交
1600 1601
    m = board.length;
    n = board[0].length;
C
CyC2018 已提交
1602

C
CyC2018 已提交
1603 1604 1605 1606 1607 1608 1609 1610
    for (int i = 0; i < m; i++) {
        dfs(board, i, 0);
        dfs(board, i, n - 1);
    }
    for (int i = 0; i < n; i++) {
        dfs(board, 0, i);
        dfs(board, m - 1, i);
    }
C
CyC2018 已提交
1611

C
CyC2018 已提交
1612 1613 1614 1615 1616 1617 1618 1619 1620
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            if (board[i][j] == 'T') {
                board[i][j] = 'O';
            } else if (board[i][j] == 'O') {
                board[i][j] = 'X';
            }
        }
    }
C
CyC2018 已提交
1621 1622
}

C
CyC2018 已提交
1623 1624 1625 1626 1627 1628 1629 1630
private void dfs(char[][] board, int r, int c) {
    if (r < 0 || r >= m || c < 0 || c >= n || board[r][c] != 'O') {
        return;
    }
    board[r][c] = 'T';
    for (int[] d : direction) {
        dfs(board, r + d[0], c + d[1]);
    }
C
CyC2018 已提交
1631 1632 1633
}
```

C
CyC2018 已提交
1634
**能到达的太平洋和大西洋的区域** 
C
CyC2018 已提交
1635

C
CyC2018 已提交
1636
[417. Pacific Atlantic Water Flow (Medium)](https://leetcode.com/problems/pacific-atlantic-water-flow/description/)
C
CyC2018 已提交
1637 1638

```html
C
CyC2018 已提交
1639
Given the following 5x5 matrix:
C
CyC2018 已提交
1640

C
CyC2018 已提交
1641 1642 1643 1644 1645 1646 1647
  Pacific ~   ~   ~   ~   ~
       ~  1   2   2   3  (5) *
       ~  3   2   3  (4) (4) *
       ~  2   4  (5)  3   1  *
       ~ (6) (7)  1   4   5  *
       ~ (5)  1   1   2   4  *
          *   *   *   *   * Atlantic
C
CyC2018 已提交
1648 1649

Return:
C
CyC2018 已提交
1650
[[0, 4], [1, 3], [1, 4], [2, 2], [3, 0], [3, 1], [4, 0]] (positions with parentheses in above matrix).
C
CyC2018 已提交
1651 1652
```

C
CyC2018 已提交
1653
左边和上边是太平洋,右边和下边是大西洋,内部的数字代表海拔,海拔高的地方的水能够流到低的地方,求解水能够流到太平洋和大西洋的所有位置。
C
CyC2018 已提交
1654 1655

```java
C
CyC2018 已提交
1656

C
CyC2018 已提交
1657 1658 1659
private int m, n;
private int[][] matrix;
private int[][] direction = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
C
CyC2018 已提交
1660

C
CyC2018 已提交
1661 1662 1663 1664 1665
public List<int[]> pacificAtlantic(int[][] matrix) {
    List<int[]> ret = new ArrayList<>();
    if (matrix == null || matrix.length == 0) {
        return ret;
    }
C
CyC2018 已提交
1666

C
CyC2018 已提交
1667 1668 1669 1670 1671
    m = matrix.length;
    n = matrix[0].length;
    this.matrix = matrix;
    boolean[][] canReachP = new boolean[m][n];
    boolean[][] canReachA = new boolean[m][n];
C
CyC2018 已提交
1672

C
CyC2018 已提交
1673 1674 1675 1676 1677 1678 1679 1680
    for (int i = 0; i < m; i++) {
        dfs(i, 0, canReachP);
        dfs(i, n - 1, canReachA);
    }
    for (int i = 0; i < n; i++) {
        dfs(0, i, canReachP);
        dfs(m - 1, i, canReachA);
    }
C
CyC2018 已提交
1681

C
CyC2018 已提交
1682 1683 1684 1685 1686 1687 1688
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            if (canReachP[i][j] && canReachA[i][j]) {
                ret.add(new int[]{i, j});
            }
        }
    }
C
CyC2018 已提交
1689

C
CyC2018 已提交
1690
    return ret;
C
CyC2018 已提交
1691 1692
}

C
CyC2018 已提交
1693 1694 1695 1696 1697 1698 1699 1700 1701 1702
private void dfs(int r, int c, boolean[][] canReach) {
    if (canReach[r][c]) {
        return;
    }
    canReach[r][c] = true;
    for (int[] d : direction) {
        int nextR = d[0] + r;
        int nextC = d[1] + c;
        if (nextR < 0 || nextR >= m || nextC < 0 || nextC >= n
                || matrix[r][c] > matrix[nextR][nextC]) {
C
CyC2018 已提交
1703

C
CyC2018 已提交
1704 1705 1706 1707
            continue;
        }
        dfs(nextR, nextC, canReach);
    }
C
CyC2018 已提交
1708 1709 1710
}
```

C
CyC2018 已提交
1711
### Backtracking
C
CyC2018 已提交
1712

C
CyC2018 已提交
1713
Backtracking(回溯)属于 DFS。
C
CyC2018 已提交
1714

C
CyC2018 已提交
1715 1716
- 普通 DFS 主要用在  **可达性问题** ,这种问题只需要执行到特点的位置然后返回即可。
- 而 Backtracking 主要用于求解  **排列组合**  问题,例如有 { 'a','b','c' } 三个字符,求解所有由这三个字符排列得到的字符串,这种问题在执行到特定的位置返回之后还会继续执行求解过程。
C
CyC2018 已提交
1717

C
CyC2018 已提交
1718
因为 Backtracking 不是立即就返回,而要继续求解,因此在程序实现时,需要注意对元素的标记问题:
C
CyC2018 已提交
1719

C
CyC2018 已提交
1720 1721
- 在访问一个新元素进入新的递归调用时,需要将新元素标记为已经访问,这样才能在继续递归调用时不用重复访问该元素;
- 但是在递归返回时,需要将元素标记为未访问,因为只需要保证在一个递归链中不同时访问一个元素,可以访问已经访问过但是不在当前递归链中的元素。
C
CyC2018 已提交
1722

C
CyC2018 已提交
1723
**数字键盘组合** 
C
CyC2018 已提交
1724

C
CyC2018 已提交
1725
[17. Letter Combinations of a Phone Number (Medium)](https://leetcode.com/problems/letter-combinations-of-a-phone-number/description/)
C
CyC2018 已提交
1726

C
CyC2018 已提交
1727
<div align="center"> <img src="pics/a3f34241-bb80-4879-8ec9-dff2d81b514e.jpg"/> </div><br>
C
CyC2018 已提交
1728 1729

```html
C
CyC2018 已提交
1730 1731
Input:Digit string "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
C
CyC2018 已提交
1732 1733 1734
```

```java
C
CyC2018 已提交
1735
private static final String[] KEYS = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
C
CyC2018 已提交
1736

C
CyC2018 已提交
1737 1738 1739 1740 1741 1742 1743
public List<String> letterCombinations(String digits) {
    List<String> combinations = new ArrayList<>();
    if (digits == null || digits.length() == 0) {
        return combinations;
    }
    doCombination(new StringBuilder(), combinations, digits);
    return combinations;
C
CyC2018 已提交
1744 1745
}

C
CyC2018 已提交
1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757
private void doCombination(StringBuilder prefix, List<String> combinations, final String digits) {
    if (prefix.length() == digits.length()) {
        combinations.add(prefix.toString());
        return;
    }
    int curDigits = digits.charAt(prefix.length()) - '0';
    String letters = KEYS[curDigits];
    for (char c : letters.toCharArray()) {
        prefix.append(c);                         // 添加
        doCombination(prefix, combinations, digits);
        prefix.deleteCharAt(prefix.length() - 1); // 删除
    }
C
CyC2018 已提交
1758 1759 1760
}
```

C
CyC2018 已提交
1761
**IP 地址划分** 
C
CyC2018 已提交
1762

C
CyC2018 已提交
1763
[93. Restore IP Addresses(Medium)](https://leetcode.com/problems/restore-ip-addresses/description/)
C
CyC2018 已提交
1764 1765

```html
C
CyC2018 已提交
1766 1767
Given "25525511135",
return ["255.255.11.135", "255.255.111.35"].
C
CyC2018 已提交
1768 1769 1770
```

```java
C
CyC2018 已提交
1771 1772 1773 1774 1775
public List<String> restoreIpAddresses(String s) {
    List<String> addresses = new ArrayList<>();
    StringBuilder tempAddress = new StringBuilder();
    doRestore(0, tempAddress, addresses, s);
    return addresses;
C
CyC2018 已提交
1776 1777
}

C
CyC2018 已提交
1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798
private void doRestore(int k, StringBuilder tempAddress, List<String> addresses, String s) {
    if (k == 4 || s.length() == 0) {
        if (k == 4 && s.length() == 0) {
            addresses.add(tempAddress.toString());
        }
        return;
    }
    for (int i = 0; i < s.length() && i <= 2; i++) {
        if (i != 0 && s.charAt(0) == '0') {
            break;
        }
        String part = s.substring(0, i + 1);
        if (Integer.valueOf(part) <= 255) {
            if (tempAddress.length() != 0) {
                part = "." + part;
            }
            tempAddress.append(part);
            doRestore(k + 1, tempAddress, addresses, s.substring(i + 1));
            tempAddress.delete(tempAddress.length() - part.length(), tempAddress.length());
        }
    }
C
CyC2018 已提交
1799 1800 1801
}
```

C
CyC2018 已提交
1802
**在矩阵中寻找字符串** 
C
CyC2018 已提交
1803

C
CyC2018 已提交
1804
[79. Word Search (Medium)](https://leetcode.com/problems/word-search/description/)
C
CyC2018 已提交
1805 1806

```html
C
CyC2018 已提交
1807 1808
For example,
Given board =
C
CyC2018 已提交
1809
[
C
CyC2018 已提交
1810 1811 1812
  ['A','B','C','E'],
  ['S','F','C','S'],
  ['A','D','E','E']
C
CyC2018 已提交
1813
]
C
CyC2018 已提交
1814 1815 1816
word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.
C
CyC2018 已提交
1817 1818 1819
```

```java
C
CyC2018 已提交
1820 1821 1822
private final static int[][] direction = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
private int m;
private int n;
C
CyC2018 已提交
1823

C
CyC2018 已提交
1824 1825 1826 1827 1828 1829 1830
public boolean exist(char[][] board, String word) {
    if (word == null || word.length() == 0) {
        return true;
    }
    if (board == null || board.length == 0 || board[0].length == 0) {
        return false;
    }
C
CyC2018 已提交
1831

C
CyC2018 已提交
1832 1833 1834
    m = board.length;
    n = board[0].length;
    boolean[][] hasVisited = new boolean[m][n];
C
CyC2018 已提交
1835

C
CyC2018 已提交
1836 1837 1838 1839 1840 1841 1842
    for (int r = 0; r < m; r++) {
        for (int c = 0; c < n; c++) {
            if (backtracking(0, r, c, hasVisited, board, word)) {
                return true;
            }
        }
    }
C
CyC2018 已提交
1843

C
CyC2018 已提交
1844
    return false;
C
CyC2018 已提交
1845 1846
}

C
CyC2018 已提交
1847 1848 1849 1850 1851 1852
private boolean backtracking(int curLen, int r, int c, boolean[][] visited, final char[][] board, final String word) {
    if (curLen == word.length()) {
        return true;
    }
    if (r < 0 || r >= m || c < 0 || c >= n
            || board[r][c] != word.charAt(curLen) || visited[r][c]) {
C
CyC2018 已提交
1853

C
CyC2018 已提交
1854 1855
        return false;
    }
C
CyC2018 已提交
1856

C
CyC2018 已提交
1857
    visited[r][c] = true;
C
CyC2018 已提交
1858

C
CyC2018 已提交
1859 1860 1861 1862 1863
    for (int[] d : direction) {
        if (backtracking(curLen + 1, r + d[0], c + d[1], visited, board, word)) {
            return true;
        }
    }
C
CyC2018 已提交
1864

C
CyC2018 已提交
1865
    visited[r][c] = false;
C
CyC2018 已提交
1866

C
CyC2018 已提交
1867
    return false;
C
CyC2018 已提交
1868 1869 1870
}
```

C
CyC2018 已提交
1871
**输出二叉树中所有从根到叶子的路径** 
C
CyC2018 已提交
1872

C
CyC2018 已提交
1873
[257. Binary Tree Paths (Easy)](https://leetcode.com/problems/binary-tree-paths/description/)
C
CyC2018 已提交
1874 1875

```html
C
CyC2018 已提交
1876 1877 1878 1879 1880
  1
 /  \
2    3
 \
  5
C
CyC2018 已提交
1881 1882 1883
```

```html
C
CyC2018 已提交
1884
["1->2->5", "1->3"]
C
CyC2018 已提交
1885 1886 1887
```

```java
C
CyC2018 已提交
1888

C
CyC2018 已提交
1889 1890 1891 1892 1893 1894 1895 1896
public List<String> binaryTreePaths(TreeNode root) {
    List<String> paths = new ArrayList<>();
    if (root == null) {
        return paths;
    }
    List<Integer> values = new ArrayList<>();
    backtracking(root, values, paths);
    return paths;
C
CyC2018 已提交
1897 1898
}

C
CyC2018 已提交
1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910
private void backtracking(TreeNode node, List<Integer> values, List<String> paths) {
    if (node == null) {
        return;
    }
    values.add(node.val);
    if (isLeaf(node)) {
        paths.add(buildPath(values));
    } else {
        backtracking(node.left, values, paths);
        backtracking(node.right, values, paths);
    }
    values.remove(values.size() - 1);
C
CyC2018 已提交
1911 1912
}

C
CyC2018 已提交
1913 1914
private boolean isLeaf(TreeNode node) {
    return node.left == null && node.right == null;
C
CyC2018 已提交
1915 1916
}

C
CyC2018 已提交
1917 1918 1919 1920 1921 1922 1923 1924 1925
private String buildPath(List<Integer> values) {
    StringBuilder str = new StringBuilder();
    for (int i = 0; i < values.size(); i++) {
        str.append(values.get(i));
        if (i != values.size() - 1) {
            str.append("->");
        }
    }
    return str.toString();
C
CyC2018 已提交
1926 1927 1928
}
```

C
CyC2018 已提交
1929
**排列** 
C
CyC2018 已提交
1930

C
CyC2018 已提交
1931
[46. Permutations (Medium)](https://leetcode.com/problems/permutations/description/)
C
CyC2018 已提交
1932 1933

```html
C
CyC2018 已提交
1934
[1,2,3] have the following permutations:
C
CyC2018 已提交
1935
[
C
CyC2018 已提交
1936 1937 1938 1939 1940 1941
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
C
CyC2018 已提交
1942 1943 1944 1945
]
```

```java
C
CyC2018 已提交
1946 1947 1948 1949 1950 1951
public List<List<Integer>> permute(int[] nums) {
    List<List<Integer>> permutes = new ArrayList<>();
    List<Integer> permuteList = new ArrayList<>();
    boolean[] hasVisited = new boolean[nums.length];
    backtracking(permuteList, permutes, hasVisited, nums);
    return permutes;
C
CyC2018 已提交
1952 1953
}

C
CyC2018 已提交
1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968
private void backtracking(List<Integer> permuteList, List<List<Integer>> permutes, boolean[] visited, final int[] nums) {
    if (permuteList.size() == nums.length) {
        permutes.add(new ArrayList<>(permuteList)); // 重新构造一个 List
        return;
    }
    for (int i = 0; i < visited.length; i++) {
        if (visited[i]) {
            continue;
        }
        visited[i] = true;
        permuteList.add(nums[i]);
        backtracking(permuteList, permutes, visited, nums);
        permuteList.remove(permuteList.size() - 1);
        visited[i] = false;
    }
C
CyC2018 已提交
1969 1970 1971
}
```

C
CyC2018 已提交
1972
**含有相同元素求排列** 
C
CyC2018 已提交
1973

C
CyC2018 已提交
1974
[47. Permutations II (Medium)](https://leetcode.com/problems/permutations-ii/description/)
C
CyC2018 已提交
1975 1976

```html
C
CyC2018 已提交
1977 1978
[1,1,2] have the following unique permutations:
[[1,1,2], [1,2,1], [2,1,1]]
C
CyC2018 已提交
1979 1980
```

C
CyC2018 已提交
1981
数组元素可能含有相同的元素,进行排列时就有可能出现重复的排列,要求重复的排列只返回一个。
C
CyC2018 已提交
1982

C
CyC2018 已提交
1983
在实现上,和 Permutations 不同的是要先排序,然后在添加一个元素时,判断这个元素是否等于前一个元素,如果等于,并且前一个元素还未访问,那么就跳过这个元素。
C
CyC2018 已提交
1984 1985

```java
C
CyC2018 已提交
1986 1987 1988 1989 1990 1991 1992
public List<List<Integer>> permuteUnique(int[] nums) {
    List<List<Integer>> permutes = new ArrayList<>();
    List<Integer> permuteList = new ArrayList<>();
    Arrays.sort(nums);  // 排序
    boolean[] hasVisited = new boolean[nums.length];
    backtracking(permuteList, permutes, hasVisited, nums);
    return permutes;
C
CyC2018 已提交
1993 1994
}

C
CyC2018 已提交
1995 1996 1997 1998 1999
private void backtracking(List<Integer> permuteList, List<List<Integer>> permutes, boolean[] visited, final int[] nums) {
    if (permuteList.size() == nums.length) {
        permutes.add(new ArrayList<>(permuteList));
        return;
    }
C
CyC2018 已提交
2000

C
CyC2018 已提交
2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013
    for (int i = 0; i < visited.length; i++) {
        if (i != 0 && nums[i] == nums[i - 1] && !visited[i - 1]) {
            continue;  // 防止重复
        }
        if (visited[i]){
            continue;
        }
        visited[i] = true;
        permuteList.add(nums[i]);
        backtracking(permuteList, permutes, visited, nums);
        permuteList.remove(permuteList.size() - 1);
        visited[i] = false;
    }
C
CyC2018 已提交
2014 2015 2016
}
```

C
CyC2018 已提交
2017
**组合** 
C
CyC2018 已提交
2018

C
CyC2018 已提交
2019
[77. Combinations (Medium)](https://leetcode.com/problems/combinations/description/)
C
CyC2018 已提交
2020 2021

```html
C
CyC2018 已提交
2022
If n = 4 and k = 2, a solution is:
C
CyC2018 已提交
2023
[
C
CyC2018 已提交
2024 2025 2026 2027 2028 2029
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
C
CyC2018 已提交
2030 2031 2032 2033
]
```

```java
C
CyC2018 已提交
2034 2035 2036 2037 2038
public List<List<Integer>> combine(int n, int k) {
    List<List<Integer>> combinations = new ArrayList<>();
    List<Integer> combineList = new ArrayList<>();
    backtracking(combineList, combinations, 1, k, n);
    return combinations;
C
CyC2018 已提交
2039 2040
}

C
CyC2018 已提交
2041 2042 2043 2044 2045 2046 2047 2048 2049 2050
private void backtracking(List<Integer> combineList, List<List<Integer>> combinations, int start, int k, final int n) {
    if (k == 0) {
        combinations.add(new ArrayList<>(combineList));
        return;
    }
    for (int i = start; i <= n - k + 1; i++) {  // 剪枝
        combineList.add(i);
        backtracking(combineList, combinations, i + 1, k - 1, n);
        combineList.remove(combineList.size() - 1);
    }
C
CyC2018 已提交
2051 2052 2053
}
```

C
CyC2018 已提交
2054
**组合求和** 
C
CyC2018 已提交
2055

C
CyC2018 已提交
2056
[39. Combination Sum (Medium)](https://leetcode.com/problems/combination-sum/description/)
C
CyC2018 已提交
2057 2058

```html
C
CyC2018 已提交
2059 2060 2061
given candidate set [2, 3, 6, 7] and target 7,
A solution set is:
[[7],[2, 2, 3]]
C
CyC2018 已提交
2062 2063 2064
```

```java
C
CyC2018 已提交
2065 2066 2067 2068
public List<List<Integer>> combinationSum(int[] candidates, int target) {
    List<List<Integer>> combinations = new ArrayList<>();
    backtracking(new ArrayList<>(), combinations, 0, target, candidates);
    return combinations;
C
CyC2018 已提交
2069
}
C
CyC2018 已提交
2070

C
CyC2018 已提交
2071 2072
private void backtracking(List<Integer> tempCombination, List<List<Integer>> combinations,
                          int start, int target, final int[] candidates) {
C
CyC2018 已提交
2073

C
CyC2018 已提交
2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084
    if (target == 0) {
        combinations.add(new ArrayList<>(tempCombination));
        return;
    }
    for (int i = start; i < candidates.length; i++) {
        if (candidates[i] <= target) {
            tempCombination.add(candidates[i]);
            backtracking(tempCombination, combinations, i, target - candidates[i], candidates);
            tempCombination.remove(tempCombination.size() - 1);
        }
    }
C
CyC2018 已提交
2085
}
C
CyC2018 已提交
2086 2087
```

C
CyC2018 已提交
2088
**含有相同元素的求组合求和** 
C
CyC2018 已提交
2089

C
CyC2018 已提交
2090
[40. Combination Sum II (Medium)](https://leetcode.com/problems/combination-sum-ii/description/)
C
CyC2018 已提交
2091 2092

```html
C
CyC2018 已提交
2093 2094
For example, given candidate set [10, 1, 2, 7, 6, 1, 5] and target 8,
A solution set is:
C
CyC2018 已提交
2095
[
C
CyC2018 已提交
2096 2097 2098 2099
  [1, 7],
  [1, 2, 5],
  [2, 6],
  [1, 1, 6]
C
CyC2018 已提交
2100 2101 2102 2103
]
```

```java
C
CyC2018 已提交
2104 2105 2106 2107 2108
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
    List<List<Integer>> combinations = new ArrayList<>();
    Arrays.sort(candidates);
    backtracking(new ArrayList<>(), combinations, new boolean[candidates.length], 0, target, candidates);
    return combinations;
C
CyC2018 已提交
2109 2110
}

C
CyC2018 已提交
2111 2112
private void backtracking(List<Integer> tempCombination, List<List<Integer>> combinations,
                          boolean[] hasVisited, int start, int target, final int[] candidates) {
C
CyC2018 已提交
2113

C
CyC2018 已提交
2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129
    if (target == 0) {
        combinations.add(new ArrayList<>(tempCombination));
        return;
    }
    for (int i = start; i < candidates.length; i++) {
        if (i != 0 && candidates[i] == candidates[i - 1] && !hasVisited[i - 1]) {
            continue;
        }
        if (candidates[i] <= target) {
            tempCombination.add(candidates[i]);
            hasVisited[i] = true;
            backtracking(tempCombination, combinations, hasVisited, i + 1, target - candidates[i], candidates);
            hasVisited[i] = false;
            tempCombination.remove(tempCombination.size() - 1);
        }
    }
C
CyC2018 已提交
2130 2131 2132
}
```

C
CyC2018 已提交
2133
**1-9 数字的组合求和** 
C
CyC2018 已提交
2134

C
CyC2018 已提交
2135
[216. Combination Sum III (Medium)](https://leetcode.com/problems/combination-sum-iii/description/)
C
CyC2018 已提交
2136 2137

```html
C
CyC2018 已提交
2138
Input: k = 3, n = 9
C
CyC2018 已提交
2139 2140 2141

Output:

C
CyC2018 已提交
2142
[[1,2,6], [1,3,5], [2,3,4]]
C
CyC2018 已提交
2143 2144
```

C
CyC2018 已提交
2145
从 1-9 数字中选出 k 个数不重复的数,使得它们的和为 n。
C
CyC2018 已提交
2146 2147

```java
C
CyC2018 已提交
2148 2149 2150 2151 2152
public List<List<Integer>> combinationSum3(int k, int n) {
    List<List<Integer>> combinations = new ArrayList<>();
    List<Integer> path = new ArrayList<>();
    backtracking(k, n, 1, path, combinations);
    return combinations;
C
CyC2018 已提交
2153 2154
}

C
CyC2018 已提交
2155 2156
private void backtracking(int k, int n, int start,
                          List<Integer> tempCombination, List<List<Integer>> combinations) {
C
CyC2018 已提交
2157

C
CyC2018 已提交
2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169
    if (k == 0 && n == 0) {
        combinations.add(new ArrayList<>(tempCombination));
        return;
    }
    if (k == 0 || n == 0) {
        return;
    }
    for (int i = start; i <= 9; i++) {
        tempCombination.add(i);
        backtracking(k - 1, n - i, i + 1, tempCombination, combinations);
        tempCombination.remove(tempCombination.size() - 1);
    }
C
CyC2018 已提交
2170 2171 2172
}
```

C
CyC2018 已提交
2173
**子集** 
C
CyC2018 已提交
2174

C
CyC2018 已提交
2175
[78. Subsets (Medium)](https://leetcode.com/problems/subsets/description/)
C
CyC2018 已提交
2176

C
CyC2018 已提交
2177
找出集合的所有子集,子集不能重复,[1, 2] 和 [2, 1] 这种子集算重复
C
CyC2018 已提交
2178 2179

```java
C
CyC2018 已提交
2180 2181 2182 2183 2184 2185 2186
public List<List<Integer>> subsets(int[] nums) {
    List<List<Integer>> subsets = new ArrayList<>();
    List<Integer> tempSubset = new ArrayList<>();
    for (int size = 0; size <= nums.length; size++) {
        backtracking(0, tempSubset, subsets, size, nums); // 不同的子集大小
    }
    return subsets;
C
CyC2018 已提交
2187 2188
}

C
CyC2018 已提交
2189 2190
private void backtracking(int start, List<Integer> tempSubset, List<List<Integer>> subsets,
                          final int size, final int[] nums) {
C
CyC2018 已提交
2191

C
CyC2018 已提交
2192 2193 2194 2195 2196 2197 2198 2199 2200
    if (tempSubset.size() == size) {
        subsets.add(new ArrayList<>(tempSubset));
        return;
    }
    for (int i = start; i < nums.length; i++) {
        tempSubset.add(nums[i]);
        backtracking(i + 1, tempSubset, subsets, size, nums);
        tempSubset.remove(tempSubset.size() - 1);
    }
C
CyC2018 已提交
2201 2202 2203
}
```

C
CyC2018 已提交
2204
**含有相同元素求子集** 
C
CyC2018 已提交
2205

C
CyC2018 已提交
2206
[90. Subsets II (Medium)](https://leetcode.com/problems/subsets-ii/description/)
C
CyC2018 已提交
2207 2208

```html
C
CyC2018 已提交
2209 2210
For example,
If nums = [1,2,2], a solution is:
C
CyC2018 已提交
2211 2212

[
C
CyC2018 已提交
2213 2214 2215 2216 2217 2218
  [2],
  [1],
  [1,2,2],
  [2,2],
  [1,2],
  []
C
CyC2018 已提交
2219 2220 2221 2222
]
```

```java
C
CyC2018 已提交
2223 2224 2225 2226 2227 2228 2229 2230 2231
public List<List<Integer>> subsetsWithDup(int[] nums) {
    Arrays.sort(nums);
    List<List<Integer>> subsets = new ArrayList<>();
    List<Integer> tempSubset = new ArrayList<>();
    boolean[] hasVisited = new boolean[nums.length];
    for (int size = 0; size <= nums.length; size++) {
        backtracking(0, tempSubset, subsets, hasVisited, size, nums); // 不同的子集大小
    }
    return subsets;
C
CyC2018 已提交
2232 2233
}

C
CyC2018 已提交
2234 2235
private void backtracking(int start, List<Integer> tempSubset, List<List<Integer>> subsets, boolean[] hasVisited,
                          final int size, final int[] nums) {
C
CyC2018 已提交
2236

C
CyC2018 已提交
2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250
    if (tempSubset.size() == size) {
        subsets.add(new ArrayList<>(tempSubset));
        return;
    }
    for (int i = start; i < nums.length; i++) {
        if (i != 0 && nums[i] == nums[i - 1] && !hasVisited[i - 1]) {
            continue;
        }
        tempSubset.add(nums[i]);
        hasVisited[i] = true;
        backtracking(i + 1, tempSubset, subsets, hasVisited, size, nums);
        hasVisited[i] = false;
        tempSubset.remove(tempSubset.size() - 1);
    }
C
CyC2018 已提交
2251 2252 2253
}
```

C
CyC2018 已提交
2254
**分割字符串使得每个部分都是回文数** 
C
CyC2018 已提交
2255

C
CyC2018 已提交
2256
[131. Palindrome Partitioning (Medium)](https://leetcode.com/problems/palindrome-partitioning/description/)
C
CyC2018 已提交
2257 2258

```html
C
CyC2018 已提交
2259
For example, given s = "aab",
C
CyC2018 已提交
2260 2261 2262
Return

[
C
CyC2018 已提交
2263 2264
  ["aa","b"],
  ["a","a","b"]
C
CyC2018 已提交
2265 2266 2267 2268
]
```

```java
C
CyC2018 已提交
2269 2270 2271 2272 2273
public List<List<String>> partition(String s) {
    List<List<String>> partitions = new ArrayList<>();
    List<String> tempPartition = new ArrayList<>();
    doPartition(s, partitions, tempPartition);
    return partitions;
C
CyC2018 已提交
2274 2275
}

C
CyC2018 已提交
2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287
private void doPartition(String s, List<List<String>> partitions, List<String> tempPartition) {
    if (s.length() == 0) {
        partitions.add(new ArrayList<>(tempPartition));
        return;
    }
    for (int i = 0; i < s.length(); i++) {
        if (isPalindrome(s, 0, i)) {
            tempPartition.add(s.substring(0, i + 1));
            doPartition(s.substring(i + 1), partitions, tempPartition);
            tempPartition.remove(tempPartition.size() - 1);
        }
    }
C
CyC2018 已提交
2288 2289
}

C
CyC2018 已提交
2290 2291 2292 2293 2294 2295 2296
private boolean isPalindrome(String s, int begin, int end) {
    while (begin < end) {
        if (s.charAt(begin++) != s.charAt(end--)) {
            return false;
        }
    }
    return true;
C
CyC2018 已提交
2297 2298 2299
}
```

C
CyC2018 已提交
2300
**数独** 
C
CyC2018 已提交
2301

C
CyC2018 已提交
2302
[37. Sudoku Solver (Hard)](https://leetcode.com/problems/sudoku-solver/description/)
C
CyC2018 已提交
2303

C
CyC2018 已提交
2304
<div align="center"> <img src="pics/1ca52246-c443-48ae-b1f8-1cafc09ec75c.png"/> </div><br>
C
CyC2018 已提交
2305 2306

```java
C
CyC2018 已提交
2307 2308 2309 2310
private boolean[][] rowsUsed = new boolean[9][10];
private boolean[][] colsUsed = new boolean[9][10];
private boolean[][] cubesUsed = new boolean[9][10];
private char[][] board;
C
CyC2018 已提交
2311

C
CyC2018 已提交
2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323
public void solveSudoku(char[][] board) {
    this.board = board;
    for (int i = 0; i < 9; i++)
        for (int j = 0; j < 9; j++) {
            if (board[i][j] == '.') {
                continue;
            }
            int num = board[i][j] - '0';
            rowsUsed[i][num] = true;
            colsUsed[j][num] = true;
            cubesUsed[cubeNum(i, j)][num] = true;
        }
C
CyC2018 已提交
2324
        backtracking(0, 0);
C
CyC2018 已提交
2325 2326
}

C
CyC2018 已提交
2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347
private boolean backtracking(int row, int col) {
    while (row < 9 && board[row][col] != '.') {
        row = col == 8 ? row + 1 : row;
        col = col == 8 ? 0 : col + 1;
    }
    if (row == 9) {
        return true;
    }
    for (int num = 1; num <= 9; num++) {
        if (rowsUsed[row][num] || colsUsed[col][num] || cubesUsed[cubeNum(row, col)][num]) {
            continue;
        }
        rowsUsed[row][num] = colsUsed[col][num] = cubesUsed[cubeNum(row, col)][num] = true;
        board[row][col] = (char) (num + '0');
        if (backtracking(row, col)) {
            return true;
        }
        board[row][col] = '.';
        rowsUsed[row][num] = colsUsed[col][num] = cubesUsed[cubeNum(row, col)][num] = false;
    }
    return false;
C
CyC2018 已提交
2348 2349
}

C
CyC2018 已提交
2350 2351 2352 2353
private int cubeNum(int i, int j) {
    int r = i / 3;
    int c = j / 3;
    return r * 3 + c;
C
CyC2018 已提交
2354 2355 2356
}
```

C
CyC2018 已提交
2357
**N 皇后** 
C
CyC2018 已提交
2358

C
CyC2018 已提交
2359
[51. N-Queens (Hard)](https://leetcode.com/problems/n-queens/description/)
C
CyC2018 已提交
2360

C
CyC2018 已提交
2361
<div align="center"> <img src="pics/1f080e53-4758-406c-bb5f-dbedf89b63ce.jpg"/> </div><br>
C
CyC2018 已提交
2362

C
CyC2018 已提交
2363
在 n\*n 的矩阵中摆放 n 个皇后,并且每个皇后不能在同一行,同一列,同一对角线上,求所有的 n 皇后的解。
C
CyC2018 已提交
2364

C
CyC2018 已提交
2365
一行一行地摆放,在确定一行中的那个皇后应该摆在哪一列时,需要用三个标记数组来确定某一列是否合法,这三个标记数组分别为:列标记数组、45 度对角线标记数组和 135 度对角线标记数组。
C
CyC2018 已提交
2366

C
CyC2018 已提交
2367 2368 2369 2370 2371 2372 2373
45 度对角线标记数组的长度为 2 \* n - 1,通过下图可以明确 (r, c) 的位置所在的数组下标为 r + c。

<div align="center"> <img src="pics/85583359-1b45-45f2-9811-4f7bb9a64db7.jpg"/> </div><br>

135 度对角线标记数组的长度也是 2 \* n - 1,(r, c) 的位置所在的数组下标为 n - 1 - (r - c)。

<div align="center"> <img src="pics/9e80f75a-b12b-4344-80c8-1f9ccc2d5246.jpg"/> </div><br>
C
CyC2018 已提交
2374

C
CyC2018 已提交
2375 2376 2377 2378 2379 2380 2381
```java
private List<List<String>> solutions;
private char[][] nQueens;
private boolean[] colUsed;
private boolean[] diagonals45Used;
private boolean[] diagonals135Used;
private int n;
C
CyC2018 已提交
2382

C
CyC2018 已提交
2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394
public List<List<String>> solveNQueens(int n) {
    solutions = new ArrayList<>();
    nQueens = new char[n][n];
    for (int i = 0; i < n; i++) {
        Arrays.fill(nQueens[i], '.');
    }
    colUsed = new boolean[n];
    diagonals45Used = new boolean[2 * n - 1];
    diagonals135Used = new boolean[2 * n - 1];
    this.n = n;
    backtracking(0);
    return solutions;
C
CyC2018 已提交
2395 2396
}

C
CyC2018 已提交
2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420
private void backtracking(int row) {
    if (row == n) {
        List<String> list = new ArrayList<>();
        for (char[] chars : nQueens) {
            list.add(new String(chars));
        }
        solutions.add(list);
        return;
    }

    for (int col = 0; col < n; col++) {
        int diagonals45Idx = row + col;
        int diagonals135Idx = n - 1 - (row - col);
        if (colUsed[col] || diagonals45Used[diagonals45Idx] || diagonals135Used[diagonals135Idx]) {
            continue;
        }
        nQueens[row][col] = 'Q';
        colUsed[col] = diagonals45Used[diagonals45Idx] = diagonals135Used[diagonals135Idx] = true;
        backtracking(row + 1);
        colUsed[col] = diagonals45Used[diagonals45Idx] = diagonals135Used[diagonals135Idx] = false;
        nQueens[row][col] = '.';
    }
}
```
C
CyC2018 已提交
2421

C
CyC2018 已提交
2422
## 动态规划
C
CyC2018 已提交
2423

C
CyC2018 已提交
2424
递归和动态规划都是将原问题拆成多个子问题然后求解,他们之间最本质的区别是,动态规划保存了子问题的解,避免重复计算。
C
CyC2018 已提交
2425

C
CyC2018 已提交
2426
### 斐波那契数列
C
CyC2018 已提交
2427

C
CyC2018 已提交
2428
**爬楼梯** 
C
CyC2018 已提交
2429

C
CyC2018 已提交
2430
[70. Climbing Stairs (Easy)](https://leetcode.com/problems/climbing-stairs/description/)
C
CyC2018 已提交
2431

C
CyC2018 已提交
2432
题目描述:有 N 阶楼梯,每次可以上一阶或者两阶,求有多少种上楼梯的方法。
C
CyC2018 已提交
2433

C
CyC2018 已提交
2434
定义一个数组 dp 存储上楼梯的方法数(为了方便讨论,数组下标从 1 开始),dp[i] 表示走到第 i 个楼梯的方法数目。
C
CyC2018 已提交
2435

C
CyC2018 已提交
2436
第 i 个楼梯可以从第 i-1 和 i-2 个楼梯再走一步到达,走到第 i 个楼梯的方法数为走到第 i-1 和第 i-2 个楼梯的方法数之和。
C
CyC2018 已提交
2437

C
CyC2018 已提交
2438
<div align="center"><img src="https://latex.codecogs.com/gif.latex?dp[i]=dp[i-1]+dp[i-2]"/></div> <br>
C
CyC2018 已提交
2439

C
CyC2018 已提交
2440
考虑到 dp[i] 只与 dp[i - 1] 和 dp[i - 2] 有关,因此可以只用两个变量来存储 dp[i - 1] 和 dp[i - 2],使得原来的 O(N) 空间复杂度优化为 O(1) 复杂度。
C
CyC2018 已提交
2441 2442

```java
C
CyC2018 已提交
2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453
public int climbStairs(int n) {
    if (n <= 2) {
        return n;
    }
    int pre2 = 1, pre1 = 2;
    for (int i = 2; i < n; i++) {
        int cur = pre1 + pre2;
        pre2 = pre1;
        pre1 = cur;
    }
    return pre1;
C
CyC2018 已提交
2454 2455 2456
}
```

C
CyC2018 已提交
2457
**强盗抢劫** 
C
CyC2018 已提交
2458

C
CyC2018 已提交
2459
[198. House Robber (Easy)](https://leetcode.com/problems/house-robber/description/)
C
CyC2018 已提交
2460 2461 2462

题目描述:抢劫一排住户,但是不能抢邻近的住户,求最大抢劫量。

C
CyC2018 已提交
2463
定义 dp 数组用来存储最大的抢劫量,其中 dp[i] 表示抢到第 i 个住户时的最大抢劫量。
C
CyC2018 已提交
2464

C
CyC2018 已提交
2465
由于不能抢劫邻近住户,如果抢劫了第 i -1 个住户,那么就不能再抢劫第 i 个住户,所以
C
CyC2018 已提交
2466

C
CyC2018 已提交
2467
<div align="center"><img src="https://latex.codecogs.com/gif.latex?dp[i]=max(dp[i-2]+nums[i],dp[i-1])"/></div> <br>
C
CyC2018 已提交
2468 2469

```java
C
CyC2018 已提交
2470 2471 2472 2473 2474 2475 2476 2477
public int rob(int[] nums) {
    int pre2 = 0, pre1 = 0;
    for (int i = 0; i < nums.length; i++) {
        int cur = Math.max(pre2 + nums[i], pre1);
        pre2 = pre1;
        pre1 = cur;
    }
    return pre1;
C
CyC2018 已提交
2478 2479 2480
}
```

C
CyC2018 已提交
2481
**强盗在环形街区抢劫** 
C
CyC2018 已提交
2482

C
CyC2018 已提交
2483
[213. House Robber II (Medium)](https://leetcode.com/problems/house-robber-ii/description/)
C
CyC2018 已提交
2484 2485

```java
C
CyC2018 已提交
2486 2487 2488 2489 2490 2491 2492 2493 2494
public  int rob(int[] nums) {
    if (nums == null || nums.length == 0) {
        return 0;
    }
    int n = nums.length;
    if (n == 1) {
        return nums[0];
    }
    return Math.max(rob(nums, 0, n - 2), rob(nums, 1, n - 1));
C
CyC2018 已提交
2495 2496
}

C
CyC2018 已提交
2497 2498 2499 2500 2501 2502 2503 2504
private   int rob(int[] nums, int first, int last) {
    int pre2 = 0, pre1 = 0;
    for (int i = first; i <= last; i++) {
        int cur = Math.max(pre1, pre2 + nums[i]);
        pre2 = pre1;
        pre1 = cur;
    }
    return pre1;
C
CyC2018 已提交
2505 2506 2507
}
```

C
CyC2018 已提交
2508
**信件错排** 
C
CyC2018 已提交
2509

C
CyC2018 已提交
2510
题目描述:有 N 个 信 和 信封,它们被打乱,求错误装信方式的数量。
C
CyC2018 已提交
2511

C
CyC2018 已提交
2512
定义一个数组 dp 存储错误方式数量,dp[i] 表示前 i 个信和信封的错误方式数量。假设第 i 个信装到第 j 个信封里面,而第 j 个信装到第 k 个信封里面。根据 i 和 k 是否相等,有两种情况:
C
CyC2018 已提交
2513

C
CyC2018 已提交
2514 2515
- i==k,交换 i 和 k 的信后,它们的信和信封在正确的位置,但是其余 i-2 封信有 dp[i-2] 种错误装信的方式。由于 j 有 i-1 种取值,因此共有 (i-1)\*dp[i-2] 种错误装信方式。
- i != k,交换 i 和 j 的信后,第 i 个信和信封在正确的位置,其余 i-1 封信有 dp[i-1] 种错误装信方式。由于 j 有 i-1 种取值,因此共有 (i-1)\*dp[i-1] 种错误装信方式。
C
CyC2018 已提交
2516 2517 2518

综上所述,错误装信数量方式数量为:

C
CyC2018 已提交
2519
<div align="center"><img src="https://latex.codecogs.com/gif.latex?dp[i]=(i-1)*dp[i-2]+(i-1)*dp[i-1]"/></div> <br>
C
CyC2018 已提交
2520

C
CyC2018 已提交
2521
**母牛生产** 
C
CyC2018 已提交
2522 2523 2524

[程序员代码面试指南-P181](#)

C
CyC2018 已提交
2525
题目描述:假设农场中成熟的母牛每年都会生 1 头小母牛,并且永远不会死。第一年有 1 只小母牛,从第二年开始,母牛开始生小母牛。每只小母牛 3 年之后成熟又可以生小母牛。给定整数 N,求 N 年后牛的数量。
C
CyC2018 已提交
2526

C
CyC2018 已提交
2527
第 i 年成熟的牛的数量为:
C
CyC2018 已提交
2528

C
CyC2018 已提交
2529
<div align="center"><img src="https://latex.codecogs.com/gif.latex?dp[i]=dp[i-1]+dp[i-3]"/></div> <br>
C
CyC2018 已提交
2530

C
CyC2018 已提交
2531
### 矩阵路径
C
CyC2018 已提交
2532

C
CyC2018 已提交
2533
**矩阵的最小路径和** 
C
CyC2018 已提交
2534

C
CyC2018 已提交
2535
[64. Minimum Path Sum (Medium)](https://leetcode.com/problems/minimum-path-sum/description/)
C
CyC2018 已提交
2536 2537 2538

```html
[[1,3,1],
C
CyC2018 已提交
2539 2540 2541
 [1,5,1],
 [4,2,1]]
Given the above grid map, return 7. Because the path 1→3→1→1→1 minimizes the sum.
C
CyC2018 已提交
2542 2543 2544 2545 2546
```

题目描述:求从矩阵的左上角到右下角的最小路径和,每次只能向右和向下移动。

```java
C
CyC2018 已提交
2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565
public int minPathSum(int[][] grid) {
    if (grid.length == 0 || grid[0].length == 0) {
        return 0;
    }
    int m = grid.length, n = grid[0].length;
    int[] dp = new int[n];
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            if (j == 0) {
                dp[j] = dp[j];        // 只能从上侧走到该位置
            } else if (i == 0) {
                dp[j] = dp[j - 1];    // 只能从左侧走到该位置
            } else {
                dp[j] = Math.min(dp[j - 1], dp[j]);
            }
            dp[j] += grid[i][j];
        }
    }
    return dp[n - 1];
C
CyC2018 已提交
2566
}
C
CyC2018 已提交
2567 2568
```

C
CyC2018 已提交
2569
**矩阵的总路径数** 
C
CyC2018 已提交
2570

C
CyC2018 已提交
2571
[62. Unique Paths (Medium)](https://leetcode.com/problems/unique-paths/description/)
C
CyC2018 已提交
2572 2573 2574

题目描述:统计从矩阵左上角到右下角的路径总数,每次只能向右或者向下移动。

C
CyC2018 已提交
2575
<div align="center"> <img src="pics/7c98e1b6-c446-4cde-8513-5c11b9f52aea.jpg"/> </div><br>
C
CyC2018 已提交
2576 2577

```java
C
CyC2018 已提交
2578 2579 2580 2581 2582 2583 2584 2585 2586
public int uniquePaths(int m, int n) {
    int[] dp = new int[n];
    Arrays.fill(dp, 1);
    for (int i = 1; i < m; i++) {
        for (int j = 1; j < n; j++) {
            dp[j] = dp[j] + dp[j - 1];
        }
    }
    return dp[n - 1];
C
CyC2018 已提交
2587 2588 2589
}
```

C
CyC2018 已提交
2590
也可以直接用数学公式求解,这是一个组合问题。机器人总共移动的次数 S=m+n-2,向下移动的次数 D=m-1,那么问题可以看成从 S 中取出 D 个位置的组合数量,这个问题的解为 C(S, D)。
C
CyC2018 已提交
2591 2592

```java
C
CyC2018 已提交
2593 2594 2595 2596 2597 2598 2599 2600
public int uniquePaths(int m, int n) {
    int S = m + n - 2;  // 总共的移动次数
    int D = m - 1;      // 向下的移动次数
    long ret = 1;
    for (int i = 1; i <= D; i++) {
        ret = ret * (S - D + i) / i;
    }
    return (int) ret;
C
CyC2018 已提交
2601 2602 2603
}
```

C
CyC2018 已提交
2604
### 数组区间
C
CyC2018 已提交
2605

C
CyC2018 已提交
2606
**数组区间和** 
C
CyC2018 已提交
2607

C
CyC2018 已提交
2608
[303. Range Sum Query - Immutable (Easy)](https://leetcode.com/problems/range-sum-query-immutable/description/)
C
CyC2018 已提交
2609 2610

```html
C
CyC2018 已提交
2611
Given nums = [-2, 0, 3, -5, 2, -1]
C
CyC2018 已提交
2612

C
CyC2018 已提交
2613 2614 2615
sumRange(0, 2) -> 1
sumRange(2, 5) -> -1
sumRange(0, 5) -> -3
C
CyC2018 已提交
2616 2617
```

C
CyC2018 已提交
2618
求区间 i \~ j 的和,可以转换为 sum[j + 1] - sum[i],其中 sum[i] 为 0 \~ i - 1 的和。
C
CyC2018 已提交
2619 2620

```java
C
CyC2018 已提交
2621
class NumArray {
C
CyC2018 已提交
2622

C
CyC2018 已提交
2623
    private int[] sums;
C
CyC2018 已提交
2624

C
CyC2018 已提交
2625 2626 2627 2628 2629 2630
    public NumArray(int[] nums) {
        sums = new int[nums.length + 1];
        for (int i = 1; i <= nums.length; i++) {
            sums[i] = sums[i - 1] + nums[i - 1];
        }
    }
C
CyC2018 已提交
2631

C
CyC2018 已提交
2632 2633 2634
    public int sumRange(int i, int j) {
        return sums[j + 1] - sums[i];
    }
C
CyC2018 已提交
2635 2636 2637
}
```

C
CyC2018 已提交
2638
**数组中等差递增子区间的个数** 
C
CyC2018 已提交
2639

C
CyC2018 已提交
2640
[413. Arithmetic Slices (Medium)](https://leetcode.com/problems/arithmetic-slices/description/)
C
CyC2018 已提交
2641 2642

```html
C
CyC2018 已提交
2643 2644
A = [1, 2, 3, 4]
return: 3, for 3 arithmetic slices in A: [1, 2, 3], [2, 3, 4] and [1, 2, 3, 4] itself.
C
CyC2018 已提交
2645 2646
```

C
CyC2018 已提交
2647
dp[i] 表示以 A[i] 为结尾的等差递增子区间的个数。
C
CyC2018 已提交
2648

C
CyC2018 已提交
2649
在 A[i] - A[i - 1] == A[i - 1] - A[i - 2] 的条件下,{A[i - 2], A[i - 1], A[i]} 是一个等差递增子区间。如果 {A[i - 3], A[i - 2], A[i - 1]} 是一个等差递增子区间,那么 {A[i - 3], A[i - 2], A[i - 1], A[i]} 也是等差递增子区间,dp[i] = dp[i-1] + 1。
C
CyC2018 已提交
2650 2651

```java
C
CyC2018 已提交
2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667
public int numberOfArithmeticSlices(int[] A) {
    if (A == null || A.length == 0) {
        return 0;
    }
    int n = A.length;
    int[] dp = new int[n];
    for (int i = 2; i < n; i++) {
        if (A[i] - A[i - 1] == A[i - 1] - A[i - 2]) {
            dp[i] = dp[i - 1] + 1;
        }
    }
    int total = 0;
    for (int cnt : dp) {
        total += cnt;
    }
    return total;
C
CyC2018 已提交
2668 2669 2670
}
```

C
CyC2018 已提交
2671
### 分割整数
C
CyC2018 已提交
2672

C
CyC2018 已提交
2673
**分割整数的最大乘积** 
C
CyC2018 已提交
2674

C
CyC2018 已提交
2675
[343. Integer Break (Medim)](https://leetcode.com/problems/integer-break/description/)
C
CyC2018 已提交
2676

C
CyC2018 已提交
2677
题目描述:For example, given n = 2, return 1 (2 = 1 + 1); given n = 10, return 36 (10 = 3 + 3 + 4).
C
CyC2018 已提交
2678 2679

```java
C
CyC2018 已提交
2680 2681 2682 2683 2684 2685 2686 2687 2688
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 - 1; j++) {
            dp[i] = Math.max(dp[i], Math.max(j * dp[i - j], j * (i - j)));
        }
    }
    return dp[n];
C
CyC2018 已提交
2689 2690 2691
}
```

C
CyC2018 已提交
2692
**按平方数来分割整数** 
C
CyC2018 已提交
2693

C
CyC2018 已提交
2694
[279. Perfect Squares(Medium)](https://leetcode.com/problems/perfect-squares/description/)
C
CyC2018 已提交
2695

C
CyC2018 已提交
2696
题目描述:For example, given n = 12, return 3 because 12 = 4 + 4 + 4; given n = 13, return 2 because 13 = 4 + 9.
C
CyC2018 已提交
2697 2698

```java
C
CyC2018 已提交
2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712
public int numSquares(int n) {
    List<Integer> squareList = generateSquareList(n);
    int[] dp = new int[n + 1];
    for (int i = 1; i <= n; i++) {
        int min = Integer.MAX_VALUE;
        for (int square : squareList) {
            if (square > i) {
                break;
            }
            min = Math.min(min, dp[i - square] + 1);
        }
        dp[i] = min;
    }
    return dp[n];
C
CyC2018 已提交
2713 2714
}

C
CyC2018 已提交
2715 2716 2717 2718 2719 2720 2721 2722 2723 2724
private List<Integer> generateSquareList(int n) {
    List<Integer> squareList = new ArrayList<>();
    int diff = 3;
    int square = 1;
    while (square <= n) {
        squareList.add(square);
        square += diff;
        diff += 2;
    }
    return squareList;
C
CyC2018 已提交
2725 2726 2727
}
```

C
CyC2018 已提交
2728
**分割整数构成字母字符串** 
C
CyC2018 已提交
2729

C
CyC2018 已提交
2730
[91. Decode Ways (Medium)](https://leetcode.com/problems/decode-ways/description/)
C
CyC2018 已提交
2731

C
CyC2018 已提交
2732
题目描述:Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12).
C
CyC2018 已提交
2733 2734

```java
C
CyC2018 已提交
2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756
public int numDecodings(String s) {
    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 已提交
2757 2758 2759
}
```

C
CyC2018 已提交
2760
### 最长递增子序列
C
CyC2018 已提交
2761

C
CyC2018 已提交
2762
已知一个序列 {S<sub>1</sub>, S<sub>2</sub>,...,S<sub>n</sub>},取出若干数组成新的序列 {S<sub>i1</sub>, S<sub>i2</sub>,..., S<sub>im</sub>},其中 i1、i2 ... im 保持递增,即新序列中各个数仍然保持原数列中的先后顺序,称新序列为原序列的一个 **子序列**
C
CyC2018 已提交
2763

C
CyC2018 已提交
2764
如果在子序列中,当下标 ix > iy 时,S<sub>ix</sub> > S<sub>iy</sub>,称子序列为原序列的一个 **递增子序列**
C
CyC2018 已提交
2765

C
CyC2018 已提交
2766
定义一个数组 dp 存储最长递增子序列的长度,dp[n] 表示以 S<sub>n</sub> 结尾的序列的最长递增子序列长度。对于一个递增子序列 {S<sub>i1</sub>, S<sub>i2</sub>,...,S<sub>im</sub>},如果 im < n 并且 S<sub>im</sub> < S<sub>n</sub>,此时 {S<sub>i1</sub>, S<sub>i2</sub>,..., S<sub>im</sub>, S<sub>n</sub>} 为一个递增子序列,递增子序列的长度增加 1。满足上述条件的递增子序列中,长度最长的那个递增子序列就是要找的,在长度最长的递增子序列上加上 S<sub>n</sub> 就构成了以 S<sub>n</sub> 为结尾的最长递增子序列。因此 dp[n] = max{ dp[i]+1 | S<sub>i</sub> < S<sub>n</sub> && i < n} 。
C
CyC2018 已提交
2767

C
CyC2018 已提交
2768
因为在求 dp[n] 时可能无法找到一个满足条件的递增子序列,此时 {S<sub>n</sub>} 就构成了递增子序列,需要对前面的求解方程做修改,令 dp[n] 最小为 1,即:
C
CyC2018 已提交
2769

C
CyC2018 已提交
2770
<div align="center"><img src="https://latex.codecogs.com/gif.latex?dp[n]=max\{1,dp[i]+1|S_i<S_n\&\&i<n\}"/></div> <br>
C
CyC2018 已提交
2771

C
CyC2018 已提交
2772
对于一个长度为 N 的序列,最长递增子序列并不一定会以 S<sub>N</sub> 为结尾,因此 dp[N] 不是序列的最长递增子序列的长度,需要遍历 dp 数组找出最大值才是所要的结果,max{ dp[i] | 1 <= i <= N} 即为所求。
C
CyC2018 已提交
2773

C
CyC2018 已提交
2774
**最长递增子序列** 
C
CyC2018 已提交
2775

C
CyC2018 已提交
2776
[300. Longest Increasing Subsequence (Medium)](https://leetcode.com/problems/longest-increasing-subsequence/description/)
C
CyC2018 已提交
2777 2778

```java
C
CyC2018 已提交
2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791
public int lengthOfLIS(int[] nums) {
    int n = nums.length;
    int[] dp = new int[n];
    for (int i = 0; i < n; i++) {
        int max = 1;
        for (int j = 0; j < i; j++) {
            if (nums[i] > nums[j]) {
                max = Math.max(max, dp[j] + 1);
            }
        }
        dp[i] = max;
    }
    return Arrays.stream(dp).max().orElse(0);
C
CyC2018 已提交
2792 2793 2794
}
```

C
CyC2018 已提交
2795
使用 Stream 求最大值会导致运行时间过长,可以改成以下形式:
C
CyC2018 已提交
2796

C
CyC2018 已提交
2797
```java
C
CyC2018 已提交
2798 2799 2800
int ret = 0;
for (int i = 0; i < n; i++) {
    ret = Math.max(ret, dp[i]);
C
CyC2018 已提交
2801
}
C
CyC2018 已提交
2802
return ret;
C
CyC2018 已提交
2803 2804
```

C
CyC2018 已提交
2805
以上解法的时间复杂度为 O(N<sup>2</sup>),可以使用二分查找将时间复杂度降低为 O(NlogN)。
C
CyC2018 已提交
2806

C
CyC2018 已提交
2807
定义一个 tails 数组,其中 tails[i] 存储长度为 i + 1 的最长递增子序列的最后一个元素。对于一个元素 x,
C
CyC2018 已提交
2808

C
CyC2018 已提交
2809 2810
- 如果它大于 tails 数组所有的值,那么把它添加到 tails 后面,表示最长递增子序列长度加 1;
- 如果 tails[i-1] < x <= tails[i],那么更新 tails[i] = x。
C
CyC2018 已提交
2811

C
CyC2018 已提交
2812
例如对于数组 [4,3,6,5],有:
C
CyC2018 已提交
2813 2814

```html
C
CyC2018 已提交
2815 2816 2817 2818 2819 2820
tails      len      num
[]         0        4
[4]        1        3
[3]        1        6
[3,6]      2        5
[3,5]      2        null
C
CyC2018 已提交
2821 2822
```

C
CyC2018 已提交
2823
可以看出 tails 数组保持有序,因此在查找 S<sub>i</sub> 位于 tails 数组的位置时就可以使用二分查找。
C
CyC2018 已提交
2824 2825

```java
C
CyC2018 已提交
2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837
public int lengthOfLIS(int[] nums) {
    int n = nums.length;
    int[] tails = new int[n];
    int len = 0;
    for (int num : nums) {
        int index = binarySearch(tails, len, num);
        tails[index] = num;
        if (index == len) {
            len++;
        }
    }
    return len;
C
CyC2018 已提交
2838 2839
}

C
CyC2018 已提交
2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852
private int binarySearch(int[] tails, int len, int key) {
    int l = 0, h = len;
    while (l < h) {
        int mid = l + (h - l) / 2;
        if (tails[mid] == key) {
            return mid;
        } else if (tails[mid] > key) {
            h = mid;
        } else {
            l = mid + 1;
        }
    }
    return l;
C
CyC2018 已提交
2853 2854 2855
}
```

C
CyC2018 已提交
2856
**一组整数对能够构成的最长链** 
C
CyC2018 已提交
2857

C
CyC2018 已提交
2858
[646. Maximum Length of Pair Chain (Medium)](https://leetcode.com/problems/maximum-length-of-pair-chain/description/)
C
CyC2018 已提交
2859 2860

```html
C
CyC2018 已提交
2861 2862 2863
Input: [[1,2], [2,3], [3,4]]
Output: 2
Explanation: The longest chain is [1,2] -> [3,4]
C
CyC2018 已提交
2864 2865
```

C
CyC2018 已提交
2866
题目描述:对于 (a, b) 和 (c, d) ,如果 b < c,则它们可以构成一条链。
C
CyC2018 已提交
2867 2868

```java
C
CyC2018 已提交
2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884
public int findLongestChain(int[][] pairs) {
    if (pairs == null || pairs.length == 0) {
        return 0;
    }
    Arrays.sort(pairs, (a, b) -> (a[0] - b[0]));
    int n = pairs.length;
    int[] dp = new int[n];
    Arrays.fill(dp, 1);
    for (int i = 1; i < n; i++) {
        for (int j = 0; j < i; j++) {
            if (pairs[j][1] < pairs[i][0]) {
                dp[i] = Math.max(dp[i], dp[j] + 1);
            }
        }
    }
    return Arrays.stream(dp).max().orElse(0);
C
CyC2018 已提交
2885 2886 2887
}
```

C
CyC2018 已提交
2888
**最长摆动子序列** 
C
CyC2018 已提交
2889

C
CyC2018 已提交
2890
[376. Wiggle Subsequence (Medium)](https://leetcode.com/problems/wiggle-subsequence/description/)
C
CyC2018 已提交
2891 2892

```html
C
CyC2018 已提交
2893 2894 2895
Input: [1,7,4,9,2,5]
Output: 6
The entire sequence is a wiggle sequence.
C
CyC2018 已提交
2896

C
CyC2018 已提交
2897 2898 2899
Input: [1,17,5,10,13,15,10,5,16,8]
Output: 7
There are several subsequences that achieve this length. One is [1,17,10,13,10,16,8].
C
CyC2018 已提交
2900

C
CyC2018 已提交
2901 2902
Input: [1,2,3,4,5,6,7,8,9]
Output: 2
C
CyC2018 已提交
2903 2904
```

C
CyC2018 已提交
2905
要求:使用 O(N) 时间复杂度求解。
C
CyC2018 已提交
2906 2907

```java
C
CyC2018 已提交
2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920
public int wiggleMaxLength(int[] nums) {
    if (nums == null || nums.length == 0) {
        return 0;
    }
    int up = 1, down = 1;
    for (int i = 1; i < nums.length; i++) {
        if (nums[i] > nums[i - 1]) {
            up = down + 1;
        } else if (nums[i] < nums[i - 1]) {
            down = up + 1;
        }
    }
    return Math.max(up, down);
C
CyC2018 已提交
2921 2922 2923
}
```

C
CyC2018 已提交
2924
### 最长公共子序列
C
CyC2018 已提交
2925

C
CyC2018 已提交
2926
对于两个子序列 S1 和 S2,找出它们最长的公共子序列。
C
CyC2018 已提交
2927

C
CyC2018 已提交
2928
定义一个二维数组 dp 用来存储最长公共子序列的长度,其中 dp[i][j] 表示 S1 的前 i 个字符与 S2 的前 j 个字符最长公共子序列的长度。考虑 S1<sub>i</sub> 与 S2<sub>j</sub> 值是否相等,分为两种情况:
C
CyC2018 已提交
2929

C
CyC2018 已提交
2930 2931
- 当 S1<sub>i</sub>==S2<sub>j</sub> 时,那么就能在 S1 的前 i-1 个字符与 S2 的前 j-1 个字符最长公共子序列的基础上再加上 S1<sub>i</sub> 这个值,最长公共子序列长度加 1,即 dp[i][j] = dp[i-1][j-1] + 1。
- 当 S1<sub>i</sub> != S2<sub>j</sub> 时,此时最长公共子序列为 S1 的前 i-1 个字符和 S2 的前 j 个字符最长公共子序列,或者 S1 的前 i 个字符和 S2 的前 j-1 个字符最长公共子序列,取它们的最大者,即 dp[i][j] = max{ dp[i-1][j], dp[i][j-1] }。
C
CyC2018 已提交
2932 2933 2934

综上,最长公共子序列的状态转移方程为:

C
CyC2018 已提交
2935
<div align="center"><img src="https://latex.codecogs.com/gif.latex?dp[i][j]=\left\{\begin{array}{rcl}dp[i-1][j-1]&&{S1_i==S2_j}\\max(dp[i-1][j],dp[i][j-1])&&{S1_i<>S2_j}\end{array}\right."/></div> <br>
C
CyC2018 已提交
2936

C
CyC2018 已提交
2937
对于长度为 N 的序列 S<sub>1</sub> 和长度为 M 的序列 S<sub>2</sub>,dp[N][M] 就是序列 S<sub>1</sub> 和序列 S<sub>2</sub> 的最长公共子序列长度。
C
CyC2018 已提交
2938 2939 2940

与最长递增子序列相比,最长公共子序列有以下不同点:

C
CyC2018 已提交
2941 2942 2943
- 针对的是两个序列,求它们的最长公共子序列。
- 在最长递增子序列中,dp[i] 表示以 S<sub>i</sub> 为结尾的最长递增子序列长度,子序列必须包含 S<sub>i</sub> ;在最长公共子序列中,dp[i][j] 表示 S1 中前 i 个字符与 S2 中前 j 个字符的最长公共子序列长度,不一定包含 S1<sub>i</sub> 和 S2<sub>j</sub>
- 在求最终解时,最长公共子序列中 dp[N][M] 就是最终解,而最长递增子序列中 dp[N] 不是最终解,因为以 S<sub>N</sub> 为结尾的最长递增子序列不一定是整个序列最长递增子序列,需要遍历一遍 dp 数组找到最大者。
C
CyC2018 已提交
2944 2945

```java
C
CyC2018 已提交
2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958
public int lengthOfLCS(int[] nums1, int[] nums2) {
    int n1 = nums1.length, n2 = nums2.length;
    int[][] dp = new int[n1 + 1][n2 + 1];
    for (int i = 1; i <= n1; i++) {
        for (int j = 1; j <= n2; j++) {
            if (nums1[i - 1] == nums2[j - 1]) {
                dp[i][j] = dp[i - 1][j - 1] + 1;
            } else {
                dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
            }
        }
    }
    return dp[n1][n2];
C
CyC2018 已提交
2959 2960 2961
}
```

C
CyC2018 已提交
2962
### 0-1 背包
C
CyC2018 已提交
2963

C
CyC2018 已提交
2964
有一个容量为 N 的背包,要用这个背包装下物品的价值最大,这些物品有两个属性:体积 w 和价值 v。
C
CyC2018 已提交
2965

C
CyC2018 已提交
2966
定义一个二维数组 dp 存储最大价值,其中 dp[i][j] 表示前 i 件物品体积不超过 j 的情况下能达到的最大价值。设第 i 件物品体积为 w,价值为 v,根据第 i 件物品是否添加到背包中,可以分两种情况讨论:
C
CyC2018 已提交
2967

C
CyC2018 已提交
2968 2969
- 第 i 件物品没添加到背包,总体积不超过 j 的前 i 件物品的最大价值就是总体积不超过 j 的前 i-1 件物品的最大价值,dp[i][j] = dp[i-1][j]
- 第 i 件物品添加到背包中,dp[i][j] = dp[i-1][j-w] + v。
C
CyC2018 已提交
2970

C
CyC2018 已提交
2971
第 i 件物品可添加也可以不添加,取决于哪种情况下最大价值更大。因此,0-1 背包的状态转移方程为:
C
CyC2018 已提交
2972

C
CyC2018 已提交
2973
<div align="center"><img src="https://latex.codecogs.com/gif.latex?dp[i][j]=max(dp[i-1][j],dp[i-1][j-w]+v)"/></div> <br>
C
CyC2018 已提交
2974 2975

```java
C
CyC2018 已提交
2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988
public int knapsack(int W, int N, int[] weights, int[] values) {
    int[][] dp = new int[N + 1][W + 1];
    for (int i = 1; i <= N; i++) {
        int w = weights[i - 1], v = values[i - 1];
        for (int j = 1; j <= W; j++) {
            if (j >= w) {
                dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - w] + v);
            } else {
                dp[i][j] = dp[i - 1][j];
            }
        }
    }
    return dp[N][W];
C
CyC2018 已提交
2989 2990 2991
}
```

C
CyC2018 已提交
2992
**空间优化** 
C
CyC2018 已提交
2993

C
CyC2018 已提交
2994
在程序实现时可以对 0-1 背包做优化。观察状态转移方程可以知道,前 i 件物品的状态仅与前 i-1 件物品的状态有关,因此可以将 dp 定义为一维数组,其中 dp[j] 既可以表示 dp[i-1][j] 也可以表示 dp[i][j]。此时,
C
CyC2018 已提交
2995

C
CyC2018 已提交
2996
<div align="center"><img src="https://latex.codecogs.com/gif.latex?dp[j]=max(dp[j],dp[j-w]+v)"/></div> <br>
C
CyC2018 已提交
2997

C
CyC2018 已提交
2998
因为 dp[j-w] 表示 dp[i-1][j-w],因此不能先求 dp[i][j-w],以防将 dp[i-1][j-w] 覆盖。也就是说要先计算 dp[i][j] 再计算 dp[i][j-w],在程序实现时需要按倒序来循环求解。
C
CyC2018 已提交
2999 3000

```java
C
CyC2018 已提交
3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011
public int knapsack(int W, int N, int[] weights, int[] values) {
    int[] dp = new int[W + 1];
    for (int i = 1; i <= N; i++) {
        int w = weights[i - 1], v = values[i - 1];
        for (int j = W; j >= 1; j--) {
            if (j >= w) {
                dp[j] = Math.max(dp[j], dp[j - w] + v);
            }
        }
    }
    return dp[W];
C
CyC2018 已提交
3012 3013 3014
}
```

C
CyC2018 已提交
3015
**无法使用贪心算法的解释** 
C
CyC2018 已提交
3016

C
CyC2018 已提交
3017
0-1 背包问题无法使用贪心算法来求解,也就是说不能按照先添加性价比最高的物品来达到最优,这是因为这种方式可能造成背包空间的浪费,从而无法达到最优。考虑下面的物品和一个容量为 5 的背包,如果先添加物品 0 再添加物品 1,那么只能存放的价值为 16,浪费了大小为 2 的空间。最优的方式是存放物品 1 和物品 2,价值为 22.
C
CyC2018 已提交
3018

C
CyC2018 已提交
3019 3020 3021 3022 3023
| id | w | v | v/w |
| --- | --- | --- | --- |
| 0 | 1 | 6 | 6 |
| 1 | 2 | 10 | 5 |
| 2 | 3 | 12 | 4 |
C
CyC2018 已提交
3024

C
CyC2018 已提交
3025
**变种** 
C
CyC2018 已提交
3026

C
CyC2018 已提交
3027
- 完全背包:物品数量为无限个
C
CyC2018 已提交
3028

C
CyC2018 已提交
3029
- 多重背包:物品数量有限制
C
CyC2018 已提交
3030

C
CyC2018 已提交
3031
- 多维费用背包:物品不仅有重量,还有体积,同时考虑这两种限制
C
CyC2018 已提交
3032

C
CyC2018 已提交
3033
- 其它:物品之间相互约束或者依赖
C
CyC2018 已提交
3034

C
CyC2018 已提交
3035
**划分数组为和相等的两部分** 
C
CyC2018 已提交
3036

C
CyC2018 已提交
3037
[416. Partition Equal Subset Sum (Medium)](https://leetcode.com/problems/partition-equal-subset-sum/description/)
C
CyC2018 已提交
3038 3039

```html
C
CyC2018 已提交
3040
Input: [1, 5, 11, 5]
C
CyC2018 已提交
3041

C
CyC2018 已提交
3042
Output: true
C
CyC2018 已提交
3043

C
CyC2018 已提交
3044
Explanation: The array can be partitioned as [1, 5, 5] and [11].
C
CyC2018 已提交
3045 3046
```

C
CyC2018 已提交
3047
可以看成一个背包大小为 sum/2 的 0-1 背包问题。
C
CyC2018 已提交
3048 3049

```java
C
CyC2018 已提交
3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063
public boolean canPartition(int[] nums) {
    int sum = computeArraySum(nums);
    if (sum % 2 != 0) {
        return false;
    }
    int W = sum / 2;
    boolean[] dp = new boolean[W + 1];
    dp[0] = true;
    for (int num : nums) {                 // 0-1 背包一个物品只能用一次
        for (int i = W; i >= num; i--) {   // 从后往前,先计算 dp[i] 再计算 dp[i-num]
            dp[i] = dp[i] || dp[i - num];
        }
    }
    return dp[W];
C
CyC2018 已提交
3064 3065
}

C
CyC2018 已提交
3066 3067 3068 3069 3070 3071
private int computeArraySum(int[] nums) {
    int sum = 0;
    for (int num : nums) {
        sum += num;
    }
    return sum;
C
CyC2018 已提交
3072 3073 3074
}
```

C
CyC2018 已提交
3075
**改变一组数的正负号使得它们的和为一给定数** 
C
CyC2018 已提交
3076

C
CyC2018 已提交
3077
[494. Target Sum (Medium)](https://leetcode.com/problems/target-sum/description/)
C
CyC2018 已提交
3078 3079

```html
C
CyC2018 已提交
3080 3081
Input: nums is [1, 1, 1, 1, 1], S is 3.
Output: 5
C
CyC2018 已提交
3082 3083
Explanation:

C
CyC2018 已提交
3084 3085 3086 3087 3088
-1+1+1+1+1 = 3
+1-1+1+1+1 = 3
+1+1-1+1+1 = 3
+1+1+1-1+1 = 3
+1+1+1+1-1 = 3
C
CyC2018 已提交
3089

C
CyC2018 已提交
3090
There are 5 ways to assign symbols to make the sum of nums be target 3.
C
CyC2018 已提交
3091 3092
```

C
CyC2018 已提交
3093
该问题可以转换为 Subset Sum 问题,从而使用 0-1 背包的方法来求解。
C
CyC2018 已提交
3094

C
CyC2018 已提交
3095
可以将这组数看成两部分,P 和 N,其中 P 使用正号,N 使用负号,有以下推导:
C
CyC2018 已提交
3096 3097

```html
C
CyC2018 已提交
3098 3099 3100
                  sum(P) - sum(N) = target
sum(P) + sum(N) + sum(P) - sum(N) = target + sum(P) + sum(N)
                       2 * sum(P) = target + sum(nums)
C
CyC2018 已提交
3101 3102
```

C
CyC2018 已提交
3103
因此只要找到一个子集,令它们都取正号,并且和等于 (target + sum(nums))/2,就证明存在解。
C
CyC2018 已提交
3104 3105

```java
C
CyC2018 已提交
3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119
public int findTargetSumWays(int[] nums, int S) {
    int sum = computeArraySum(nums);
    if (sum < S || (sum + S) % 2 == 1) {
        return 0;
    }
    int W = (sum + S) / 2;
    int[] dp = new int[W + 1];
    dp[0] = 1;
    for (int num : nums) {
        for (int i = W; i >= num; i--) {
            dp[i] = dp[i] + dp[i - num];
        }
    }
    return dp[W];
C
CyC2018 已提交
3120
}
C
CyC2018 已提交
3121

C
CyC2018 已提交
3122 3123 3124 3125 3126 3127
private int computeArraySum(int[] nums) {
    int sum = 0;
    for (int num : nums) {
        sum += num;
    }
    return sum;
C
CyC2018 已提交
3128
}
C
CyC2018 已提交
3129 3130
```

C
CyC2018 已提交
3131
DFS 解法:
C
CyC2018 已提交
3132 3133

```java
C
CyC2018 已提交
3134 3135
public int findTargetSumWays(int[] nums, int S) {
    return findTargetSumWays(nums, 0, S);
C
CyC2018 已提交
3136 3137
}

C
CyC2018 已提交
3138 3139 3140 3141 3142 3143
private int findTargetSumWays(int[] nums, int start, int S) {
    if (start == nums.length) {
        return S == 0 ? 1 : 0;
    }
    return findTargetSumWays(nums, start + 1, S + nums[start])
            + findTargetSumWays(nums, start + 1, S - nums[start]);
C
CyC2018 已提交
3144 3145 3146
}
```

C
CyC2018 已提交
3147
**01 字符构成最多的字符串** 
C
CyC2018 已提交
3148

C
CyC2018 已提交
3149
[474. Ones and Zeroes (Medium)](https://leetcode.com/problems/ones-and-zeroes/description/)
C
CyC2018 已提交
3150 3151

```html
C
CyC2018 已提交
3152 3153
Input: Array = {"10", "0001", "111001", "1", "0"}, m = 5, n = 3
Output: 4
C
CyC2018 已提交
3154

C
CyC2018 已提交
3155
Explanation: There are totally 4 strings can be formed by the using of 5 0s and 3 1s, which are "10","0001","1","0"
C
CyC2018 已提交
3156 3157
```

C
CyC2018 已提交
3158
这是一个多维费用的 0-1 背包问题,有两个背包大小,0 的数量和 1 的数量。
C
CyC2018 已提交
3159 3160

```java
C
CyC2018 已提交
3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181
public int findMaxForm(String[] strs, int m, int n) {
    if (strs == null || strs.length == 0) {
        return 0;
    }
    int[][] dp = new int[m + 1][n + 1];
    for (String s : strs) {    // 每个字符串只能用一次
        int ones = 0, zeros = 0;
        for (char c : s.toCharArray()) {
            if (c == '0') {
                zeros++;
            } else {
                ones++;
            }
        }
        for (int i = m; i >= zeros; i--) {
            for (int j = n; j >= ones; j--) {
                dp[i][j] = Math.max(dp[i][j], dp[i - zeros][j - ones] + 1);
            }
        }
    }
    return dp[m][n];
C
CyC2018 已提交
3182 3183 3184
}
```

C
CyC2018 已提交
3185
**找零钱的最少硬币数** 
C
CyC2018 已提交
3186

C
CyC2018 已提交
3187
[322. Coin Change (Medium)](https://leetcode.com/problems/coin-change/description/)
C
CyC2018 已提交
3188 3189

```html
C
CyC2018 已提交
3190 3191 3192
Example 1:
coins = [1, 2, 5], amount = 11
return 3 (11 = 5 + 5 + 1)
C
CyC2018 已提交
3193

C
CyC2018 已提交
3194 3195 3196
Example 2:
coins = [2], amount = 3
return -1.
C
CyC2018 已提交
3197 3198 3199 3200
```

题目描述:给一些面额的硬币,要求用这些硬币来组成给定面额的钱数,并且使得硬币数量最少。硬币可以重复使用。

C
CyC2018 已提交
3201 3202 3203
- 物品:硬币
- 物品大小:面额
- 物品价值:数量
C
CyC2018 已提交
3204

C
CyC2018 已提交
3205
因为硬币可以重复使用,因此这是一个完全背包问题。完全背包只需要将 0-1 背包中逆序遍历 dp 数组改为正序遍历即可。
C
CyC2018 已提交
3206 3207

```java
C
CyC2018 已提交
3208
public int coinChange(int[] coins, int amount) {
C
CyC2018 已提交
3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221
    if (amount == 0 || coins == null || coins.length == 0) {
        return 0;
    }
    int[] dp = new int[amount + 1];
    for (int coin : coins) {
        for (int i = coin; i <= amount; i++) { //将逆序遍历改为正序遍历
            if (i == coin) {
                dp[i] = 1;
            } else if (dp[i] == 0 && dp[i - coin] != 0) {
                dp[i] = dp[i - coin] + 1;
            } else if (dp[i - coin] != 0) {
                dp[i] = Math.min(dp[i], dp[i - coin] + 1);
            }
5
5renyuebing 已提交
3222 3223
        }
    }
C
CyC2018 已提交
3224
    return dp[amount] == 0 ? -1 : dp[amount];
5
5renyuebing 已提交
3225 3226 3227 3228 3229
}
```

**找零钱的硬币数组合** 

C
CyC2018 已提交
3230
[518\. Coin Change 2 (Medium)](https://leetcode.com/problems/coin-change-2/description/)
5
5renyuebing 已提交
3231

C
CyC2018 已提交
3232
```text-html-basic
5
5renyuebing 已提交
3233 3234 3235 3236 3237 3238 3239 3240 3241
Input: amount = 5, coins = [1, 2, 5]
Output: 4
Explanation: there are four ways to make up the amount:
5=5
5=2+2+1
5=2+1+1+1
5=1+1+1+1+1
```

C
CyC2018 已提交
3242
完全背包问题,使用 dp 记录可达成目标的组合数目。
5
5renyuebing 已提交
3243 3244 3245

```java
public int change(int amount, int[] coins) {
C
CyC2018 已提交
3246 3247 3248
    if (amount == 0 || coins == null || coins.length == 0) {
        return 0;
    }
5
5renyuebing 已提交
3249 3250
    int[] dp = new int[amount + 1];
    dp[0] = 1;
C
CyC2018 已提交
3251 3252
    for (int coin : coins) {
        for (int i = coin; i <= amount; i++) {
5
5renyuebing 已提交
3253 3254
            dp[i] += dp[i - coin];
        }
C
CyC2018 已提交
3255
    }
5
5renyuebing 已提交
3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271
    return dp[amount];
}
```

**字符串按单词列表分割** 

[139. Word Break (Medium)](https://leetcode.com/problems/word-break/description/)

```html
s = "leetcode",
dict = ["leet", "code"].
Return true because "leetcode" can be segmented as "leet code".
```

dict 中的单词没有使用次数的限制,因此这是一个完全背包问题。该问题涉及到字典中单词的使用顺序,因此可理解为涉及顺序的完全背包问题。

C
CyC2018 已提交
3272
求解顺序的完全背包问题时,对物品的迭代应该放在最里层。
5
5renyuebing 已提交
3273 3274 3275 3276 3277 3278 3279

```java
public boolean wordBreak(String s, List<String> wordDict) {
    int n = s.length();
    boolean[] dp = new boolean[n + 1];
    dp[0] = true;
    for (int i = 1; i <= n; i++) {
C
CyC2018 已提交
3280
        for (String word : wordDict) {   // 对物品的迭代应该放在最里层
5
5renyuebing 已提交
3281 3282 3283 3284
            int len = word.length();
            if (len <= i && word.equals(s.substring(i - len, i))) {
                dp[i] = dp[i] || dp[i - len];
            }
C
CyC2018 已提交
3285 3286
        }
    }
5
5renyuebing 已提交
3287
    return dp[n];
C
CyC2018 已提交
3288 3289 3290
}
```

C
CyC2018 已提交
3291
**组合总和** 
C
CyC2018 已提交
3292

C
CyC2018 已提交
3293
[377. Combination Sum IV (Medium)](https://leetcode.com/problems/combination-sum-iv/description/)
C
CyC2018 已提交
3294

C
CyC2018 已提交
3295
```html
C
CyC2018 已提交
3296 3297
nums = [1, 2, 3]
target = 4
C
CyC2018 已提交
3298

C
CyC2018 已提交
3299 3300 3301 3302 3303 3304 3305 3306
The possible combination ways are:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1)
C
CyC2018 已提交
3307

C
CyC2018 已提交
3308
Note that different sequences are counted as different combinations.
C
CyC2018 已提交
3309

C
CyC2018 已提交
3310
Therefore the output is 7.
C
CyC2018 已提交
3311 3312
```

5
5renyuebing 已提交
3313
涉及顺序的完全背包。
C
CyC2018 已提交
3314 3315

```java
C
CyC2018 已提交
3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328
public int combinationSum4(int[] nums, int target) {
    if (nums == null || nums.length == 0) {
        return 0;
    }
    int[] maximum = new int[target + 1];
    maximum[0] = 1;
    Arrays.sort(nums);
    for (int i = 1; i <= target; i++) {
        for (int j = 0; j < nums.length && nums[j] <= i; j++) {
            maximum[i] += maximum[i - nums[j]];
        }
    }
    return maximum[target];
C
CyC2018 已提交
3329 3330 3331
}
```

C
CyC2018 已提交
3332
### 股票交易
C
CyC2018 已提交
3333

C
CyC2018 已提交
3334
**需要冷却期的股票交易** 
C
CyC2018 已提交
3335

C
CyC2018 已提交
3336
[309. Best Time to Buy and Sell Stock with Cooldown(Medium)](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/description/)
C
CyC2018 已提交
3337 3338 3339

题目描述:交易之后需要有一天的冷却时间。

C
CyC2018 已提交
3340
<div align="center"> <img src="pics/a3da4342-078b-43e2-b748-7e71bec50dc4.png"/> </div><br>
C
CyC2018 已提交
3341 3342

```java
C
CyC2018 已提交
3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360
public int maxProfit(int[] prices) {
    if (prices == null || prices.length == 0) {
        return 0;
    }
    int N = prices.length;
    int[] buy = new int[N];
    int[] s1 = new int[N];
    int[] sell = new int[N];
    int[] s2 = new int[N];
    s1[0] = buy[0] = -prices[0];
    sell[0] = s2[0] = 0;
    for (int i = 1; i < N; i++) {
        buy[i] = s2[i - 1] - prices[i];
        s1[i] = Math.max(buy[i - 1], s1[i - 1]);
        sell[i] = Math.max(buy[i - 1], s1[i - 1]) + prices[i];
        s2[i] = Math.max(s2[i - 1], sell[i - 1]);
    }
    return Math.max(sell[N - 1], s2[N - 1]);
C
CyC2018 已提交
3361 3362 3363
}
```

C
CyC2018 已提交
3364
**需要交易费用的股票交易** 
C
CyC2018 已提交
3365

C
CyC2018 已提交
3366
[714. Best Time to Buy and Sell Stock with Transaction Fee (Medium)](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/description/)
C
CyC2018 已提交
3367 3368

```html
C
CyC2018 已提交
3369 3370 3371 3372 3373 3374 3375 3376
Input: prices = [1, 3, 2, 8, 4, 9], fee = 2
Output: 8
Explanation: The maximum profit can be achieved by:
Buying at prices[0] = 1
Selling at prices[3] = 8
Buying at prices[4] = 4
Selling at prices[5] = 9
The total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8.
C
CyC2018 已提交
3377 3378 3379 3380
```

题目描述:每交易一次,都要支付一定的费用。

C
CyC2018 已提交
3381
<div align="center"> <img src="pics/61942711-45a0-4e11-bbc9-434e31436f33.png"/> </div><br>
C
CyC2018 已提交
3382 3383

```java
C
CyC2018 已提交
3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398
public int maxProfit(int[] prices, int fee) {
    int N = prices.length;
    int[] buy = new int[N];
    int[] s1 = new int[N];
    int[] sell = new int[N];
    int[] s2 = new int[N];
    s1[0] = buy[0] = -prices[0];
    sell[0] = s2[0] = 0;
    for (int i = 1; i < N; i++) {
        buy[i] = Math.max(sell[i - 1], s2[i - 1]) - prices[i];
        s1[i] = Math.max(buy[i - 1], s1[i - 1]);
        sell[i] = Math.max(buy[i - 1], s1[i - 1]) - fee + prices[i];
        s2[i] = Math.max(s2[i - 1], sell[i - 1]);
    }
    return Math.max(sell[N - 1], s2[N - 1]);
C
CyC2018 已提交
3399 3400 3401 3402
}
```


C
CyC2018 已提交
3403
**只能进行两次的股票交易** 
C
CyC2018 已提交
3404

C
CyC2018 已提交
3405
[123. Best Time to Buy and Sell Stock III (Hard)](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/description/)
C
CyC2018 已提交
3406 3407

```java
C
CyC2018 已提交
3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425
public int maxProfit(int[] prices) {
    int firstBuy = Integer.MIN_VALUE, firstSell = 0;
    int secondBuy = Integer.MIN_VALUE, secondSell = 0;
    for (int curPrice : prices) {
        if (firstBuy < -curPrice) {
            firstBuy = -curPrice;
        }
        if (firstSell < firstBuy + curPrice) {
            firstSell = firstBuy + curPrice;
        }
        if (secondBuy < firstSell - curPrice) {
            secondBuy = firstSell - curPrice;
        }
        if (secondSell < secondBuy + curPrice) {
            secondSell = secondBuy + curPrice;
        }
    }
    return secondSell;
C
CyC2018 已提交
3426 3427 3428
}
```

C
CyC2018 已提交
3429
**只能进行 k 次的股票交易** 
C
CyC2018 已提交
3430

C
CyC2018 已提交
3431
[188. Best Time to Buy and Sell Stock IV (Hard)](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/description/)
C
CyC2018 已提交
3432 3433

```java
C
CyC2018 已提交
3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453
public int maxProfit(int k, int[] prices) {
    int n = prices.length;
    if (k >= n / 2) {   // 这种情况下该问题退化为普通的股票交易问题
        int maxProfit = 0;
        for (int i = 1; i < n; i++) {
            if (prices[i] > prices[i - 1]) {
                maxProfit += prices[i] - prices[i - 1];
            }
        }
        return maxProfit;
    }
    int[][] maxProfit = new int[k + 1][n];
    for (int i = 1; i <= k; i++) {
        int localMax = maxProfit[i - 1][0] - prices[0];
        for (int j = 1; j < n; j++) {
            maxProfit[i][j] = Math.max(maxProfit[i][j - 1], prices[j] + localMax);
            localMax = Math.max(localMax, maxProfit[i - 1][j] - prices[j]);
        }
    }
    return maxProfit[k][n - 1];
C
CyC2018 已提交
3454 3455 3456
}
```

C
CyC2018 已提交
3457
### 字符串编辑
C
CyC2018 已提交
3458

C
CyC2018 已提交
3459
**删除两个字符串的字符使它们相等** 
C
CyC2018 已提交
3460

C
CyC2018 已提交
3461
[583. Delete Operation for Two Strings (Medium)](https://leetcode.com/problems/delete-operation-for-two-strings/description/)
C
CyC2018 已提交
3462 3463

```html
C
CyC2018 已提交
3464 3465 3466
Input: "sea", "eat"
Output: 2
Explanation: You need one step to make "sea" to "ea" and another step to make "eat" to "ea".
C
CyC2018 已提交
3467 3468 3469 3470 3471
```

可以转换为求两个字符串的最长公共子序列问题。

```java
C
CyC2018 已提交
3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484
public int minDistance(String word1, String word2) {
    int m = word1.length(), n = word2.length();
    int[][] dp = new int[m + 1][n + 1];
    for (int i = 1; i <= m; i++) {
        for (int j = 1; j <= n; j++) {
            if (word1.charAt(i - 1) == word2.charAt(j - 1)) {
                dp[i][j] = dp[i - 1][j - 1] + 1;
            } else {
                dp[i][j] = Math.max(dp[i][j - 1], dp[i - 1][j]);
            }
        }
    }
    return m + n - 2 * dp[m][n];
C
CyC2018 已提交
3485 3486 3487
}
```

C
CyC2018 已提交
3488
**编辑距离** 
C
CyC2018 已提交
3489

C
CyC2018 已提交
3490
[72. Edit Distance (Hard)](https://leetcode.com/problems/edit-distance/description/)
C
CyC2018 已提交
3491 3492

```html
C
CyC2018 已提交
3493
Example 1:
C
CyC2018 已提交
3494

C
CyC2018 已提交
3495 3496
Input: word1 = "horse", word2 = "ros"
Output: 3
C
CyC2018 已提交
3497
Explanation:
C
CyC2018 已提交
3498 3499 3500 3501
horse -> rorse (replace 'h' with 'r')
rorse -> rose (remove 'r')
rose -> ros (remove 'e')
Example 2:
C
CyC2018 已提交
3502

C
CyC2018 已提交
3503 3504
Input: word1 = "intention", word2 = "execution"
Output: 5
C
CyC2018 已提交
3505
Explanation:
C
CyC2018 已提交
3506 3507 3508 3509 3510
intention -> inention (remove 't')
inention -> enention (replace 'i' with 'e')
enention -> exention (replace 'n' with 'x')
exention -> exection (replace 'n' with 'c')
exection -> execution (insert 'u')
C
CyC2018 已提交
3511 3512 3513 3514 3515
```

题目描述:修改一个字符串成为另一个字符串,使得修改次数最少。一次修改操作包括:插入一个字符、删除一个字符、替换一个字符。

```java
C
CyC2018 已提交
3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537
public int minDistance(String word1, String word2) {
    if (word1 == null || word2 == null) {
        return 0;
    }
    int m = word1.length(), n = word2.length();
    int[][] dp = new int[m + 1][n + 1];
    for (int i = 1; i <= m; i++) {
        dp[i][0] = i;
    }
    for (int i = 1; i <= n; i++) {
        dp[0][i] = i;
    }
    for (int i = 1; i <= m; i++) {
        for (int j = 1; j <= n; j++) {
            if (word1.charAt(i - 1) == word2.charAt(j - 1)) {
                dp[i][j] = dp[i - 1][j - 1];
            } else {
                dp[i][j] = Math.min(dp[i - 1][j - 1], Math.min(dp[i][j - 1], dp[i - 1][j])) + 1;
            }
        }
    }
    return dp[m][n];
C
CyC2018 已提交
3538 3539 3540
}
```

C
CyC2018 已提交
3541
**复制粘贴字符** 
C
CyC2018 已提交
3542

C
CyC2018 已提交
3543
[650. 2 Keys Keyboard (Medium)](https://leetcode.com/problems/2-keys-keyboard/description/)
C
CyC2018 已提交
3544

C
CyC2018 已提交
3545
题目描述:最开始只有一个字符 A,问需要多少次操作能够得到 n 个字符 A,每次操作可以复制当前所有的字符,或者粘贴。
C
CyC2018 已提交
3546 3547

```
C
CyC2018 已提交
3548 3549
Input: 3
Output: 3
C
CyC2018 已提交
3550
Explanation:
C
CyC2018 已提交
3551 3552 3553 3554
Intitally, we have one character 'A'.
In step 1, we use Copy All operation.
In step 2, we use Paste operation to get 'AA'.
In step 3, we use Paste operation to get 'AAA'.
C
CyC2018 已提交
3555 3556
```

C
CyC2018 已提交
3557
```java
C
CyC2018 已提交
3558 3559 3560 3561 3562 3563
public int minSteps(int n) {
    if (n == 1) return 0;
    for (int i = 2; i <= Math.sqrt(n); i++) {
        if (n % i == 0) return i + minSteps(n / i);
    }
    return n;
C
CyC2018 已提交
3564 3565 3566
}
```

C
CyC2018 已提交
3567
```java
C
CyC2018 已提交
3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580
public int minSteps(int n) {
    int[] dp = new int[n + 1];
    int h = (int) Math.sqrt(n);
    for (int i = 2; i <= n; i++) {
        dp[i] = i;
        for (int j = 2; j <= h; j++) {
            if (i % j == 0) {
                dp[i] = dp[j] + dp[i / j];
                break;
            }
        }
    }
    return dp[n];
C
CyC2018 已提交
3581 3582 3583
}
```

C
CyC2018 已提交
3584
## 数学
C
CyC2018 已提交
3585

C
CyC2018 已提交
3586
### 素数
C
CyC2018 已提交
3587

C
CyC2018 已提交
3588
**素数分解** 
C
CyC2018 已提交
3589

C
CyC2018 已提交
3590
每一个数都可以分解成素数的乘积,例如 84 = 2<sup>2</sup> \* 3<sup>1</sup> \* 5<sup>0</sup> \* 7<sup>1</sup> \* 11<sup>0</sup> \* 13<sup>0</sup> \* 17<sup>0</sup> \*
C
CyC2018 已提交
3591

C
CyC2018 已提交
3592
**整除** 
C
CyC2018 已提交
3593

C
CyC2018 已提交
3594
令 x = 2<sup>m0</sup> \* 3<sup>m1</sup> \* 5<sup>m2</sup> \* 7<sup>m3</sup> \* 11<sup>m4</sup> \*
C
CyC2018 已提交
3595

C
CyC2018 已提交
3596
令 y = 2<sup>n0</sup> \* 3<sup>n1</sup> \* 5<sup>n2</sup> \* 7<sup>n3</sup> \* 11<sup>n4</sup> \*
C
CyC2018 已提交
3597

C
CyC2018 已提交
3598
如果 x 整除 y(y mod x == 0),则对于所有 i,mi <= ni。
C
CyC2018 已提交
3599

C
CyC2018 已提交
3600
**最大公约数最小公倍数** 
C
CyC2018 已提交
3601

C
CyC2018 已提交
3602
x 和 y 的最大公约数为:gcd(x,y) =  2<sup>min(m0,n0)</sup> \* 3<sup>min(m1,n1)</sup> \* 5<sup>min(m2,n2)</sup> \* ...
C
CyC2018 已提交
3603

C
CyC2018 已提交
3604
x 和 y 的最小公倍数为:lcm(x,y) =  2<sup>max(m0,n0)</sup> \* 3<sup>max(m1,n1)</sup> \* 5<sup>max(m2,n2)</sup> \* ...
C
CyC2018 已提交
3605

C
CyC2018 已提交
3606
**生成素数序列** 
C
CyC2018 已提交
3607

C
CyC2018 已提交
3608
[204. Count Primes (Easy)](https://leetcode.com/problems/count-primes/description/)
C
CyC2018 已提交
3609 3610 3611 3612

埃拉托斯特尼筛法在每次找到一个素数时,将能被素数整除的数排除掉。

```java
C
CyC2018 已提交
3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626
public int countPrimes(int n) {
    boolean[] notPrimes = new boolean[n + 1];
    int count = 0;
    for (int i = 2; i < n; i++) {
        if (notPrimes[i]) {
            continue;
        }
        count++;
        // 从 i * i 开始,因为如果 k < i,那么 k * i 在之前就已经被去除过了
        for (long j = (long) (i) * i; j < n; j += i) {
            notPrimes[(int) j] = true;
        }
    }
    return count;
C
CyC2018 已提交
3627 3628 3629
}
```

C
CyC2018 已提交
3630
### 最大公约数
C
CyC2018 已提交
3631 3632

```java
C
CyC2018 已提交
3633 3634
int gcd(int a, int b) {
    return b == 0 ? a : gcd(b, a % b);
C
CyC2018 已提交
3635 3636 3637 3638 3639 3640
}
```

最小公倍数为两数的乘积除以最大公约数。

```java
C
CyC2018 已提交
3641 3642
int lcm(int a, int b) {
    return a * b / gcd(a, b);
C
CyC2018 已提交
3643 3644 3645
}
```

C
CyC2018 已提交
3646
**使用位操作和减法求解最大公约数** 
C
CyC2018 已提交
3647 3648

[编程之美:2.7](#)
C
CyC2018 已提交
3649

C
CyC2018 已提交
3650
对于 a 和 b 的最大公约数 f(a, b),有:
C
CyC2018 已提交
3651

C
CyC2018 已提交
3652 3653 3654 3655
- 如果 a 和 b 均为偶数,f(a, b) = 2\*f(a/2, b/2);
- 如果 a 是偶数 b 是奇数,f(a, b) = f(a/2, b);
- 如果 b 是偶数 a 是奇数,f(a, b) = f(a, b/2);
- 如果 a 和 b 均为奇数,f(a, b) = f(b, a-b);
C
CyC2018 已提交
3656

C
CyC2018 已提交
3657
乘 2 和除 2 都可以转换为移位操作。
C
CyC2018 已提交
3658

C
CyC2018 已提交
3659
```java
C
CyC2018 已提交
3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676
public int gcd(int a, int b) {
    if (a < b) {
        return gcd(b, a);
    }
    if (b == 0) {
        return a;
    }
    boolean isAEven = isEven(a), isBEven = isEven(b);
    if (isAEven && isBEven) {
        return 2 * gcd(a >> 1, b >> 1);
    } else if (isAEven && !isBEven) {
        return gcd(a >> 1, b);
    } else if (!isAEven && isBEven) {
        return gcd(a, b >> 1);
    } else {
        return gcd(b, a - b);
    }
C
CyC2018 已提交
3677 3678 3679
}
```

C
CyC2018 已提交
3680
### 进制转换
C
CyC2018 已提交
3681

C
CyC2018 已提交
3682
**7 进制** 
C
CyC2018 已提交
3683

C
CyC2018 已提交
3684
[504. Base 7 (Easy)](https://leetcode.com/problems/base-7/description/)
C
CyC2018 已提交
3685 3686

```java
C
CyC2018 已提交
3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701
public String convertToBase7(int num) {
    if (num == 0) {
        return "0";
    }
    StringBuilder sb = new StringBuilder();
    boolean isNegative = num < 0;
    if (isNegative) {
        num = -num;
    }
    while (num > 0) {
        sb.append(num % 7);
        num /= 7;
    }
    String ret = sb.reverse().toString();
    return isNegative ? "-" + ret : ret;
C
CyC2018 已提交
3702 3703 3704
}
```

C
CyC2018 已提交
3705
Java 中 static String toString(int num, int radix) 可以将一个整数转换为 radix 进制表示的字符串。
C
CyC2018 已提交
3706 3707

```java
C
CyC2018 已提交
3708 3709
public String convertToBase7(int num) {
    return Integer.toString(num, 7);
C
CyC2018 已提交
3710 3711 3712
}
```

C
CyC2018 已提交
3713
**16 进制** 
C
CyC2018 已提交
3714

C
CyC2018 已提交
3715
[405. Convert a Number to Hexadecimal (Easy)](https://leetcode.com/problems/convert-a-number-to-hexadecimal/description/)
C
CyC2018 已提交
3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730

```html
Input:
26

Output:
"1a"

Input:
-1

Output:
"ffffffff"
```

C
CyC2018 已提交
3731 3732
负数要用它的补码形式。

C
CyC2018 已提交
3733
```java
C
CyC2018 已提交
3734 3735 3736 3737 3738 3739 3740 3741 3742
public String toHex(int num) {
    char[] map = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
    if (num == 0) return "0";
    StringBuilder sb = new StringBuilder();
    while (num != 0) {
        sb.append(map[num & 0b1111]);
        num >>>= 4; // 因为考虑的是补码形式,因此符号位就不能有特殊的意义,需要使用无符号右移,左边填 0
    }
    return sb.reverse().toString();
C
CyC2018 已提交
3743 3744 3745
}
```

C
CyC2018 已提交
3746
**26 进制** 
C
CyC2018 已提交
3747

C
CyC2018 已提交
3748
[168. Excel Sheet Column Title (Easy)](https://leetcode.com/problems/excel-sheet-column-title/description/)
C
CyC2018 已提交
3749 3750

```html
C
CyC2018 已提交
3751 3752 3753
1 -> A
2 -> B
3 -> C
C
CyC2018 已提交
3754
...
C
CyC2018 已提交
3755 3756 3757
26 -> Z
27 -> AA
28 -> AB
C
CyC2018 已提交
3758 3759
```

C
CyC2018 已提交
3760
因为是从 1 开始计算的,而不是从 0 开始,因此需要对 n 执行 -1 操作。
C
CyC2018 已提交
3761 3762

```java
C
CyC2018 已提交
3763 3764 3765 3766 3767 3768
public String convertToTitle(int n) {
    if (n == 0) {
        return "";
    }
    n--;
    return convertToTitle(n / 26) + (char) (n % 26 + 'A');
C
CyC2018 已提交
3769 3770 3771
}
```

C
CyC2018 已提交
3772
### 阶乘
C
CyC2018 已提交
3773

C
CyC2018 已提交
3774
**统计阶乘尾部有多少个 0** 
C
CyC2018 已提交
3775

C
CyC2018 已提交
3776
[172. Factorial Trailing Zeroes (Easy)](https://leetcode.com/problems/factorial-trailing-zeroes/description/)
C
CyC2018 已提交
3777

C
CyC2018 已提交
3778
尾部的 0 由 2 * 5 得来,2 的数量明显多于 5 的数量,因此只要统计有多少个 5 即可。
C
CyC2018 已提交
3779

C
CyC2018 已提交
3780
对于一个数 N,它所包含 5 的个数为:N/5 + N/5<sup>2</sup> + N/5<sup>3</sup> + ...,其中 N/5 表示不大于 N 的数中 5 的倍数贡献一个 5,N/5<sup>2</sup> 表示不大于 N 的数中 5<sup>2</sup> 的倍数再贡献一个 5 ...。
C
CyC2018 已提交
3781 3782

```java
C
CyC2018 已提交
3783 3784
public int trailingZeroes(int n) {
    return n == 0 ? 0 : n / 5 + trailingZeroes(n / 5);
C
CyC2018 已提交
3785 3786 3787
}
```

C
CyC2018 已提交
3788
如果统计的是 N! 的二进制表示中最低位 1 的位置,只要统计有多少个 2 即可,该题目出自 [编程之美:2.2](#) 。和求解有多少个 5 一样,2 的个数为 N/2 + N/2<sup>2</sup> + N/2<sup>3</sup> + ...
C
CyC2018 已提交
3789

C
CyC2018 已提交
3790
### 字符串加法减法
C
CyC2018 已提交
3791

C
CyC2018 已提交
3792
**二进制加法** 
C
CyC2018 已提交
3793

C
CyC2018 已提交
3794
[67. Add Binary (Easy)](https://leetcode.com/problems/add-binary/description/)
C
CyC2018 已提交
3795 3796

```html
C
CyC2018 已提交
3797 3798 3799
a = "11"
b = "1"
Return "100".
C
CyC2018 已提交
3800 3801 3802
```

```java
C
CyC2018 已提交
3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816
public String addBinary(String a, String b) {
    int i = a.length() - 1, j = b.length() - 1, carry = 0;
    StringBuilder str = new StringBuilder();
    while (carry == 1 || i >= 0 || j >= 0) {
        if (i >= 0 && a.charAt(i--) == '1') {
            carry++;
        }
        if (j >= 0 && b.charAt(j--) == '1') {
            carry++;
        }
        str.append(carry % 2);
        carry /= 2;
    }
    return str.reverse().toString();
C
CyC2018 已提交
3817 3818 3819
}
```

C
CyC2018 已提交
3820
**字符串加法** 
C
CyC2018 已提交
3821

C
CyC2018 已提交
3822
[415. Add Strings (Easy)](https://leetcode.com/problems/add-strings/description/)
C
CyC2018 已提交
3823

C
CyC2018 已提交
3824
字符串的值为非负整数。
C
CyC2018 已提交
3825 3826

```java
C
CyC2018 已提交
3827 3828 3829 3830 3831 3832 3833 3834 3835 3836
public String addStrings(String num1, String num2) {
    StringBuilder str = new StringBuilder();
    int carry = 0, i = num1.length() - 1, j = num2.length() - 1;
    while (carry == 1 || i >= 0 || j >= 0) {
        int x = i < 0 ? 0 : num1.charAt(i--) - '0';
        int y = j < 0 ? 0 : num2.charAt(j--) - '0';
        str.append((x + y + carry) % 10);
        carry = (x + y + carry) / 10;
    }
    return str.reverse().toString();
C
CyC2018 已提交
3837 3838 3839
}
```

C
CyC2018 已提交
3840
### 相遇问题
C
CyC2018 已提交
3841

C
CyC2018 已提交
3842
**改变数组元素使所有的数组元素都相等** 
C
CyC2018 已提交
3843

C
CyC2018 已提交
3844
[462. Minimum Moves to Equal Array Elements II (Medium)](https://leetcode.com/problems/minimum-moves-to-equal-array-elements-ii/description/)
C
CyC2018 已提交
3845 3846 3847 3848 3849 3850 3851 3852 3853

```html
Input:
[1,2,3]

Output:
2

Explanation:
C
CyC2018 已提交
3854
Only two moves are needed (remember each move increments or decrements one element):
C
CyC2018 已提交
3855

C
CyC2018 已提交
3856
[1,2,3]  =>  [2,2,3]  =>  [2,2,2]
C
CyC2018 已提交
3857 3858 3859 3860 3861 3862
```

每次可以对一个数组元素加一或者减一,求最小的改变次数。

这是个典型的相遇问题,移动距离最小的方式是所有元素都移动到中位数。理由如下:

C
CyC2018 已提交
3863
设 m 为中位数。a 和 b 是 m 两边的两个元素,且 b > a。要使 a 和 b 相等,它们总共移动的次数为 b - a,这个值等于 (b - m) + (m - a),也就是把这两个数移动到中位数的移动次数。
C
CyC2018 已提交
3864

C
CyC2018 已提交
3865
设数组长度为 N,则可以找到 N/2 对 a 和 b 的组合,使它们都移动到 m 的位置。
C
CyC2018 已提交
3866

C
CyC2018 已提交
3867
**解法 1** 
C
CyC2018 已提交
3868 3869 3870 3871

先排序,时间复杂度:O(NlogN)

```java
C
CyC2018 已提交
3872 3873 3874 3875 3876 3877 3878 3879 3880 3881
public int minMoves2(int[] nums) {
    Arrays.sort(nums);
    int move = 0;
    int l = 0, h = nums.length - 1;
    while (l <= h) {
        move += nums[h] - nums[l];
        l++;
        h--;
    }
    return move;
C
CyC2018 已提交
3882 3883 3884
}
```

C
CyC2018 已提交
3885
**解法 2** 
C
CyC2018 已提交
3886

C
CyC2018 已提交
3887
使用快速选择找到中位数,时间复杂度 O(N)
C
CyC2018 已提交
3888 3889

```java
C
CyC2018 已提交
3890 3891 3892 3893 3894 3895 3896
public int minMoves2(int[] nums) {
    int move = 0;
    int median = findKthSmallest(nums, nums.length / 2);
    for (int num : nums) {
        move += Math.abs(num - median);
    }
    return move;
C
CyC2018 已提交
3897 3898
}

C
CyC2018 已提交
3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912
private int findKthSmallest(int[] nums, int k) {
    int l = 0, h = nums.length - 1;
    while (l < h) {
        int j = partition(nums, l, h);
        if (j == k) {
            break;
        }
        if (j < k) {
            l = j + 1;
        } else {
            h = j - 1;
        }
    }
    return nums[k];
C
CyC2018 已提交
3913 3914
}

C
CyC2018 已提交
3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926
private int partition(int[] nums, int l, int h) {
    int i = l, j = h + 1;
    while (true) {
        while (nums[++i] < nums[l] && i < h) ;
        while (nums[--j] > nums[l] && j > l) ;
        if (i >= j) {
            break;
        }
        swap(nums, i, j);
    }
    swap(nums, l, j);
    return j;
C
CyC2018 已提交
3927 3928
}

C
CyC2018 已提交
3929 3930 3931 3932
private void swap(int[] nums, int i, int j) {
    int tmp = nums[i];
    nums[i] = nums[j];
    nums[j] = tmp;
C
CyC2018 已提交
3933 3934 3935
}
```

C
CyC2018 已提交
3936
### 多数投票问题
C
CyC2018 已提交
3937

C
CyC2018 已提交
3938
**数组中出现次数多于 n / 2 的元素** 
C
CyC2018 已提交
3939

C
CyC2018 已提交
3940
[169. Majority Element (Easy)](https://leetcode.com/problems/majority-element/description/)
C
CyC2018 已提交
3941

C
CyC2018 已提交
3942
先对数组排序,最中间那个数出现次数一定多于 n / 2。
C
CyC2018 已提交
3943 3944

```java
C
CyC2018 已提交
3945 3946 3947
public int majorityElement(int[] nums) {
    Arrays.sort(nums);
    return nums[nums.length / 2];
C
CyC2018 已提交
3948 3949 3950
}
```

C
CyC2018 已提交
3951
可以利用 Boyer-Moore Majority Vote Algorithm 来解决这个问题,使得时间复杂度为 O(N)。可以这么理解该算法:使用 cnt 来统计一个元素出现的次数,当遍历到的元素和统计元素不相等时,令 cnt--。如果前面查找了 i 个元素,且 cnt == 0,说明前 i 个元素没有 majority,或者有 majority,但是出现的次数少于 i / 2,因为如果多于 i / 2 的话 cnt 就一定不会为 0。此时剩下的 n - i 个元素中,majority 的数目依然多于 (n - i) / 2,因此继续查找就能找出 majority。
C
CyC2018 已提交
3952 3953

```java
C
CyC2018 已提交
3954 3955 3956 3957 3958 3959 3960
public int majorityElement(int[] nums) {
    int cnt = 0, majority = nums[0];
    for (int num : nums) {
        majority = (cnt == 0) ? num : majority;
        cnt = (majority == num) ? cnt + 1 : cnt - 1;
    }
    return majority;
C
CyC2018 已提交
3961 3962 3963
}
```

C
CyC2018 已提交
3964
### 其它
C
CyC2018 已提交
3965

C
CyC2018 已提交
3966
**平方数** 
C
CyC2018 已提交
3967

C
CyC2018 已提交
3968
[367. Valid Perfect Square (Easy)](https://leetcode.com/problems/valid-perfect-square/description/)
C
CyC2018 已提交
3969 3970

```html
C
CyC2018 已提交
3971 3972
Input: 16
Returns: True
C
CyC2018 已提交
3973 3974 3975
```

平方序列:1,4,9,16,..
C
CyC2018 已提交
3976

C
CyC2018 已提交
3977 3978
间隔:3,5,7,...

C
CyC2018 已提交
3979
间隔为等差数列,使用这个特性可以得到从 1 开始的平方序列。
C
CyC2018 已提交
3980 3981

```java
C
CyC2018 已提交
3982 3983 3984 3985 3986 3987 3988
public boolean isPerfectSquare(int num) {
    int subNum = 1;
    while (num > 0) {
        num -= subNum;
        subNum += 2;
    }
    return num == 0;
C
CyC2018 已提交
3989 3990 3991
}
```

C
CyC2018 已提交
3992
**3 的 n 次方** 
C
CyC2018 已提交
3993

C
CyC2018 已提交
3994
[326. Power of Three (Easy)](https://leetcode.com/problems/power-of-three/description/)
C
CyC2018 已提交
3995 3996

```java
C
CyC2018 已提交
3997 3998
public boolean isPowerOfThree(int n) {
    return n > 0 && (1162261467 % n == 0);
C
CyC2018 已提交
3999 4000 4001
}
```

C
CyC2018 已提交
4002
**乘积数组** 
C
CyC2018 已提交
4003

C
CyC2018 已提交
4004
[238. Product of Array Except Self (Medium)](https://leetcode.com/problems/product-of-array-except-self/description/)
C
CyC2018 已提交
4005 4006

```html
C
CyC2018 已提交
4007
For example, given [1,2,3,4], return [24,12,8,6].
C
CyC2018 已提交
4008 4009
```

C
CyC2018 已提交
4010
给定一个数组,创建一个新数组,新数组的每个元素为原始数组中除了该位置上的元素之外所有元素的乘积。
C
CyC2018 已提交
4011

C
CyC2018 已提交
4012
要求时间复杂度为 O(N),并且不能使用除法。
C
CyC2018 已提交
4013 4014

```java
C
CyC2018 已提交
4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029
public int[] productExceptSelf(int[] nums) {
    int n = nums.length;
    int[] products = new int[n];
    Arrays.fill(products, 1);
    int left = 1;
    for (int i = 1; i < n; i++) {
        left *= nums[i - 1];
        products[i] *= left;
    }
    int right = 1;
    for (int i = n - 2; i >= 0; i--) {
        right *= nums[i + 1];
        products[i] *= right;
    }
    return products;
C
CyC2018 已提交
4030 4031 4032
}
```

C
CyC2018 已提交
4033
**找出数组中的乘积最大的三个数** 
C
CyC2018 已提交
4034

C
CyC2018 已提交
4035
[628. Maximum Product of Three Numbers (Easy)](https://leetcode.com/problems/maximum-product-of-three-numbers/description/)
C
CyC2018 已提交
4036 4037

```html
C
CyC2018 已提交
4038 4039
Input: [1,2,3,4]
Output: 24
C
CyC2018 已提交
4040 4041 4042
```

```java
C
CyC2018 已提交
4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055
public int maximumProduct(int[] nums) {
    int max1 = Integer.MIN_VALUE, max2 = Integer.MIN_VALUE, max3 = Integer.MIN_VALUE, min1 = Integer.MAX_VALUE, min2 = Integer.MAX_VALUE;
    for (int n : nums) {
        if (n > max1) {
            max3 = max2;
            max2 = max1;
            max1 = n;
        } else if (n > max2) {
            max3 = max2;
            max2 = n;
        } else if (n > max3) {
            max3 = n;
        }
C
CyC2018 已提交
4056

C
CyC2018 已提交
4057 4058 4059 4060 4061 4062 4063 4064
        if (n < min1) {
            min2 = min1;
            min1 = n;
        } else if (n < min2) {
            min2 = n;
        }
    }
    return Math.max(max1*max2*max3, max1*min1*min2);
C
CyC2018 已提交
4065 4066 4067
}
```

C
CyC2018 已提交
4068
# 数据结构相关
C
CyC2018 已提交
4069

C
CyC2018 已提交
4070
## 链表
C
CyC2018 已提交
4071

C
CyC2018 已提交
4072
链表是空节点,或者有一个值和一个指向下一个链表的指针,因此很多链表问题可以用递归来处理。
C
CyC2018 已提交
4073

C
CyC2018 已提交
4074
**找出两个链表的交点** 
C
CyC2018 已提交
4075

C
CyC2018 已提交
4076
[160. Intersection of Two Linked Lists (Easy)](https://leetcode.com/problems/intersection-of-two-linked-lists/description/)
C
CyC2018 已提交
4077

C
CyC2018 已提交
4078
```html
C
CyC2018 已提交
4079 4080 4081 4082 4083
A:          a1 → a2

                      c1 → c2 → c3

B:    b1 → b2 → b3
C
CyC2018 已提交
4084 4085
```

C
CyC2018 已提交
4086
要求:时间复杂度为 O(N),空间复杂度为 O(1)
C
CyC2018 已提交
4087

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

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

```java
C
CyC2018 已提交
4093 4094 4095 4096 4097 4098 4099
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
    ListNode l1 = headA, l2 = headB;
    while (l1 != l2) {
        l1 = (l1 == null) ? headB : l1.next;
        l2 = (l2 == null) ? headA : l2.next;
    }
    return l1;
C
CyC2018 已提交
4100 4101 4102
}
```

C
CyC2018 已提交
4103
如果只是判断是否存在交点,那么就是另一个问题,即 [编程之美 3.6]() 的问题。有两种解法:
C
CyC2018 已提交
4104

C
CyC2018 已提交
4105 4106
- 把第一个链表的结尾连接到第二个链表的开头,看第二个链表是否存在环;
- 或者直接比较两个链表的最后一个节点是否相同。
C
CyC2018 已提交
4107

C
CyC2018 已提交
4108
**链表反转** 
C
CyC2018 已提交
4109

C
CyC2018 已提交
4110
[206. Reverse Linked List (Easy)](https://leetcode.com/problems/reverse-linked-list/description/)
C
CyC2018 已提交
4111

C
CyC2018 已提交
4112
递归
C
CyC2018 已提交
4113 4114

```java
C
CyC2018 已提交
4115 4116 4117 4118 4119 4120 4121 4122 4123
public ListNode reverseList(ListNode head) {
    if (head == null || head.next == null) {
        return head;
    }
    ListNode next = head.next;
    ListNode newHead = reverseList(next);
    next.next = head;
    head.next = null;
    return newHead;
C
CyC2018 已提交
4124 4125 4126
}
```

C
CyC2018 已提交
4127
头插法
C
CyC2018 已提交
4128 4129

```java
C
CyC2018 已提交
4130 4131 4132 4133 4134 4135 4136 4137 4138
public ListNode reverseList(ListNode head) {
    ListNode newHead = new ListNode(-1);
    while (head != null) {
        ListNode next = head.next;
        head.next = newHead.next;
        newHead.next = head;
        head = next;
    }
    return newHead.next;
C
CyC2018 已提交
4139 4140 4141
}
```

C
CyC2018 已提交
4142
**归并两个有序的链表** 
C
CyC2018 已提交
4143

C
CyC2018 已提交
4144
[21. Merge Two Sorted Lists (Easy)](https://leetcode.com/problems/merge-two-sorted-lists/description/)
C
CyC2018 已提交
4145 4146

```java
C
CyC2018 已提交
4147 4148 4149 4150 4151 4152 4153 4154 4155 4156
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
    if (l1 == null) return l2;
    if (l2 == null) return l1;
    if (l1.val < l2.val) {
        l1.next = mergeTwoLists(l1.next, l2);
        return l1;
    } else {
        l2.next = mergeTwoLists(l1, l2.next);
        return l2;
    }
C
CyC2018 已提交
4157 4158 4159
}
```

C
CyC2018 已提交
4160
**从有序链表中删除重复节点** 
C
CyC2018 已提交
4161

C
CyC2018 已提交
4162
[83. Remove Duplicates from Sorted List (Easy)](https://leetcode.com/problems/remove-duplicates-from-sorted-list/description/)
C
CyC2018 已提交
4163

C
CyC2018 已提交
4164
```html
C
CyC2018 已提交
4165 4166
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.
C
CyC2018 已提交
4167
```
C
CyC2018 已提交
4168

C
CyC2018 已提交
4169
```java
C
CyC2018 已提交
4170 4171 4172 4173
public ListNode deleteDuplicates(ListNode head) {
    if (head == null || head.next == null) return head;
    head.next = deleteDuplicates(head.next);
    return head.val == head.next.val ? head.next : head;
C
CyC2018 已提交
4174 4175
}
```
C
CyC2018 已提交
4176

C
CyC2018 已提交
4177
**删除链表的倒数第 n 个节点** 
C
CyC2018 已提交
4178

C
CyC2018 已提交
4179
[19. Remove Nth Node From End of List (Medium)](https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/)
C
CyC2018 已提交
4180

C
CyC2018 已提交
4181
```html
C
CyC2018 已提交
4182 4183
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.
C
CyC2018 已提交
4184
```
C
CyC2018 已提交
4185 4186

```java
C
CyC2018 已提交
4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199
public ListNode removeNthFromEnd(ListNode head, int n) {
    ListNode fast = head;
    while (n-- > 0) {
        fast = fast.next;
    }
    if (fast == null) return head.next;
    ListNode slow = head;
    while (fast.next != null) {
        fast = fast.next;
        slow = slow.next;
    }
    slow.next = slow.next.next;
    return head;
C
CyC2018 已提交
4200 4201 4202
}
```

C
CyC2018 已提交
4203
**交换链表中的相邻结点** 
C
CyC2018 已提交
4204

C
CyC2018 已提交
4205
[24. Swap Nodes in Pairs (Medium)](https://leetcode.com/problems/swap-nodes-in-pairs/description/)
C
CyC2018 已提交
4206 4207

```html
C
CyC2018 已提交
4208
Given 1->2->3->4, you should return the list as 2->1->4->3.
C
CyC2018 已提交
4209 4210
```

C
CyC2018 已提交
4211
题目要求:不能修改结点的 val 值,O(1) 空间复杂度。
C
CyC2018 已提交
4212 4213

```java
C
CyC2018 已提交
4214 4215 4216 4217 4218 4219 4220 4221 4222 4223
public ListNode swapPairs(ListNode head) {
    ListNode node = new ListNode(-1);
    node.next = head;
    ListNode pre = node;
    while (pre.next != null && pre.next.next != null) {
        ListNode l1 = pre.next, l2 = pre.next.next;
        ListNode next = l2.next;
        l1.next = next;
        l2.next = l1;
        pre.next = l2;
C
CyC2018 已提交
4224

C
CyC2018 已提交
4225 4226 4227
        pre = l1;
    }
    return node.next;
C
CyC2018 已提交
4228 4229 4230
}
```

C
CyC2018 已提交
4231
**链表求和** 
C
CyC2018 已提交
4232

C
CyC2018 已提交
4233
[445. Add Two Numbers II (Medium)](https://leetcode.com/problems/add-two-numbers-ii/description/)
C
CyC2018 已提交
4234 4235

```html
C
CyC2018 已提交
4236 4237
Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7
C
CyC2018 已提交
4238 4239
```

C
CyC2018 已提交
4240
题目要求:不能修改原始链表。
C
CyC2018 已提交
4241 4242

```java
C
CyC2018 已提交
4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    Stack<Integer> l1Stack = buildStack(l1);
    Stack<Integer> l2Stack = buildStack(l2);
    ListNode head = new ListNode(-1);
    int carry = 0;
    while (!l1Stack.isEmpty() || !l2Stack.isEmpty() || carry != 0) {
        int x = l1Stack.isEmpty() ? 0 : l1Stack.pop();
        int y = l2Stack.isEmpty() ? 0 : l2Stack.pop();
        int sum = x + y + carry;
        ListNode node = new ListNode(sum % 10);
        node.next = head.next;
        head.next = node;
        carry = sum / 10;
    }
    return head.next;
C
CyC2018 已提交
4258 4259
}

C
CyC2018 已提交
4260 4261 4262 4263 4264 4265 4266
private Stack<Integer> buildStack(ListNode l) {
    Stack<Integer> stack = new Stack<>();
    while (l != null) {
        stack.push(l.val);
        l = l.next;
    }
    return stack;
C
CyC2018 已提交
4267 4268 4269
}
```

C
CyC2018 已提交
4270
**回文链表** 
C
CyC2018 已提交
4271

C
CyC2018 已提交
4272
[234. Palindrome Linked List (Easy)](https://leetcode.com/problems/palindrome-linked-list/description/)
C
CyC2018 已提交
4273

C
CyC2018 已提交
4274
题目要求:以 O(1) 的空间复杂度来求解。
C
CyC2018 已提交
4275

C
CyC2018 已提交
4276
切成两半,把后半段反转,然后比较两半是否相等。
C
CyC2018 已提交
4277

C
CyC2018 已提交
4278
```java
C
CyC2018 已提交
4279 4280 4281 4282 4283 4284 4285 4286 4287 4288
public boolean isPalindrome(ListNode head) {
    if (head == null || head.next == null) return true;
    ListNode slow = head, fast = head.next;
    while (fast != null && fast.next != null) {
        slow = slow.next;
        fast = fast.next.next;
    }
    if (fast != null) slow = slow.next;  // 偶数节点,让 slow 指向下一个节点
    cut(head, slow);                     // 切成两个链表
    return isEqual(head, reverse(slow));
C
CyC2018 已提交
4289 4290
}

C
CyC2018 已提交
4291 4292 4293 4294 4295
private void cut(ListNode head, ListNode cutNode) {
    while (head.next != cutNode) {
        head = head.next;
    }
    head.next = null;
C
CyC2018 已提交
4296 4297
}

C
CyC2018 已提交
4298 4299 4300 4301 4302 4303 4304 4305 4306
private ListNode reverse(ListNode head) {
    ListNode newHead = null;
    while (head != null) {
        ListNode nextNode = head.next;
        head.next = newHead;
        newHead = head;
        head = nextNode;
    }
    return newHead;
C
CyC2018 已提交
4307
}
C
CyC2018 已提交
4308

C
CyC2018 已提交
4309 4310 4311 4312 4313 4314 4315
private boolean isEqual(ListNode l1, ListNode l2) {
    while (l1 != null && l2 != null) {
        if (l1.val != l2.val) return false;
        l1 = l1.next;
        l2 = l2.next;
    }
    return true;
C
CyC2018 已提交
4316
}
C
CyC2018 已提交
4317 4318
```

C
CyC2018 已提交
4319
**分隔链表** 
C
CyC2018 已提交
4320

C
CyC2018 已提交
4321
[725. Split Linked List in Parts(Medium)](https://leetcode.com/problems/split-linked-list-in-parts/description/)
C
CyC2018 已提交
4322 4323

```html
C
CyC2018 已提交
4324
Input:
C
CyC2018 已提交
4325 4326
root = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], k = 3
Output: [[1, 2, 3, 4], [5, 6, 7], [8, 9, 10]]
C
CyC2018 已提交
4327
Explanation:
C
CyC2018 已提交
4328
The input has been split into consecutive parts with size difference at most 1, and earlier parts are a larger size than the later parts.
C
CyC2018 已提交
4329 4330
```

C
CyC2018 已提交
4331
题目描述:把链表分隔成 k 部分,每部分的长度都应该尽可能相同,排在前面的长度应该大于等于后面的。
C
CyC2018 已提交
4332 4333

```java
C
CyC2018 已提交
4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355
public ListNode[] splitListToParts(ListNode root, int k) {
    int N = 0;
    ListNode cur = root;
    while (cur != null) {
        N++;
        cur = cur.next;
    }
    int mod = N % k;
    int size = N / k;
    ListNode[] ret = new ListNode[k];
    cur = root;
    for (int i = 0; cur != null && i < k; i++) {
        ret[i] = cur;
        int curSize = size + (mod-- > 0 ? 1 : 0);
        for (int j = 0; j < curSize - 1; j++) {
            cur = cur.next;
        }
        ListNode next = cur.next;
        cur.next = null;
        cur = next;
    }
    return ret;
C
CyC2018 已提交
4356 4357 4358
}
```

C
CyC2018 已提交
4359
**链表元素按奇偶聚集** 
C
CyC2018 已提交
4360

C
CyC2018 已提交
4361
[328. Odd Even Linked List (Medium)](https://leetcode.com/problems/odd-even-linked-list/description/)
C
CyC2018 已提交
4362 4363 4364

```html
Example:
C
CyC2018 已提交
4365 4366
Given 1->2->3->4->5->NULL,
return 1->3->5->2->4->NULL.
C
CyC2018 已提交
4367 4368 4369
```

```java
C
CyC2018 已提交
4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382
public ListNode oddEvenList(ListNode head) {
    if (head == null) {
        return head;
    }
    ListNode odd = head, even = head.next, evenHead = even;
    while (even != null && even.next != null) {
        odd.next = odd.next.next;
        odd = odd.next;
        even.next = even.next.next;
        even = even.next;
    }
    odd.next = evenHead;
    return head;
C
CyC2018 已提交
4383 4384 4385
}
```

C
CyC2018 已提交
4386
## 树
C
CyC2018 已提交
4387

C
CyC2018 已提交
4388
### 递归
C
CyC2018 已提交
4389

C
CyC2018 已提交
4390
一棵树要么是空树,要么有两个指针,每个指针指向一棵树。树是一种递归结构,很多树的问题可以使用递归来处理。
C
CyC2018 已提交
4391

C
CyC2018 已提交
4392
**树的高度** 
C
CyC2018 已提交
4393

C
CyC2018 已提交
4394
[104. Maximum Depth of Binary Tree (Easy)](https://leetcode.com/problems/maximum-depth-of-binary-tree/description/)
C
CyC2018 已提交
4395 4396

```java
C
CyC2018 已提交
4397 4398 4399
public int maxDepth(TreeNode root) {
    if (root == null) return 0;
    return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
C
CyC2018 已提交
4400 4401 4402
}
```

C
CyC2018 已提交
4403
**平衡树** 
C
CyC2018 已提交
4404

C
CyC2018 已提交
4405
[110. Balanced Binary Tree (Easy)](https://leetcode.com/problems/balanced-binary-tree/description/)
C
CyC2018 已提交
4406 4407

```html
C
CyC2018 已提交
4408 4409 4410 4411 4412
    3
   / \
  9  20
    /  \
   15   7
C
CyC2018 已提交
4413 4414
```

C
CyC2018 已提交
4415
平衡树左右子树高度差都小于等于 1
C
CyC2018 已提交
4416 4417

```java
C
CyC2018 已提交
4418
private boolean result = true;
C
CyC2018 已提交
4419

C
CyC2018 已提交
4420 4421 4422
public boolean isBalanced(TreeNode root) {
    maxDepth(root);
    return result;
C
CyC2018 已提交
4423 4424
}

C
CyC2018 已提交
4425 4426 4427 4428 4429 4430
public int maxDepth(TreeNode root) {
    if (root == null) return 0;
    int l = maxDepth(root.left);
    int r = maxDepth(root.right);
    if (Math.abs(l - r) > 1) result = false;
    return 1 + Math.max(l, r);
C
CyC2018 已提交
4431 4432 4433
}
```

C
CyC2018 已提交
4434
**两节点的最长路径** 
C
CyC2018 已提交
4435

C
CyC2018 已提交
4436
[543. Diameter of Binary Tree (Easy)](https://leetcode.com/problems/diameter-of-binary-tree/description/)
C
CyC2018 已提交
4437 4438

```html
C
CyC2018 已提交
4439
Input:
C
CyC2018 已提交
4440

C
CyC2018 已提交
4441 4442 4443 4444 4445
         1
        / \
       2  3
      / \
     4   5
C
CyC2018 已提交
4446

C
CyC2018 已提交
4447
Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].
C
CyC2018 已提交
4448
```
C
CyC2018 已提交
4449 4450

```java
C
CyC2018 已提交
4451
private int max = 0;
C
CyC2018 已提交
4452

C
CyC2018 已提交
4453 4454 4455
public int diameterOfBinaryTree(TreeNode root) {
    depth(root);
    return max;
C
CyC2018 已提交
4456 4457
}

C
CyC2018 已提交
4458 4459 4460 4461 4462 4463
private int depth(TreeNode root) {
    if (root == null) return 0;
    int leftDepth = depth(root.left);
    int rightDepth = depth(root.right);
    max = Math.max(max, leftDepth + rightDepth);
    return Math.max(leftDepth, rightDepth) + 1;
C
CyC2018 已提交
4464 4465 4466
}
```

C
CyC2018 已提交
4467
**翻转树** 
C
CyC2018 已提交
4468

C
CyC2018 已提交
4469
[226. Invert Binary Tree (Easy)](https://leetcode.com/problems/invert-binary-tree/description/)
C
CyC2018 已提交
4470 4471

```java
C
CyC2018 已提交
4472 4473 4474 4475 4476 4477
public TreeNode invertTree(TreeNode root) {
    if (root == null) return null;
    TreeNode left = root.left;  // 后面的操作会改变 left 指针,因此先保存下来
    root.left = invertTree(root.right);
    root.right = invertTree(left);
    return root;
C
CyC2018 已提交
4478 4479 4480
}
```

C
CyC2018 已提交
4481
**归并两棵树** 
C
CyC2018 已提交
4482

C
CyC2018 已提交
4483
[617. Merge Two Binary Trees (Easy)](https://leetcode.com/problems/merge-two-binary-trees/description/)
C
CyC2018 已提交
4484 4485

```html
C
CyC2018 已提交
4486
Input:
C
CyC2018 已提交
4487 4488 4489 4490 4491 4492
       Tree 1                     Tree 2
          1                         2
         / \                       / \
        3   2                     1   3
       /                           \   \
      5                             4   7
C
CyC2018 已提交
4493 4494

Output:
C
CyC2018 已提交
4495 4496 4497 4498 4499
         3
        / \
       4   5
      / \   \
     5   4   7
C
CyC2018 已提交
4500 4501 4502
```

```java
C
CyC2018 已提交
4503 4504 4505 4506 4507 4508 4509 4510
public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
    if (t1 == null && t2 == null) return null;
    if (t1 == null) return t2;
    if (t2 == null) return t1;
    TreeNode root = new TreeNode(t1.val + t2.val);
    root.left = mergeTrees(t1.left, t2.left);
    root.right = mergeTrees(t1.right, t2.right);
    return root;
C
CyC2018 已提交
4511 4512 4513
}
```

C
CyC2018 已提交
4514
**判断路径和是否等于一个数** 
C
CyC2018 已提交
4515

C
CyC2018 已提交
4516
[Leetcdoe : 112. Path Sum (Easy)](https://leetcode.com/problems/path-sum/description/)
C
CyC2018 已提交
4517 4518

```html
C
CyC2018 已提交
4519
Given the below binary tree and sum = 22,
C
CyC2018 已提交
4520

C
CyC2018 已提交
4521 4522 4523 4524 4525 4526 4527
              5
             / \
            4   8
           /   / \
          11  13  4
         /  \      \
        7    2      1
C
CyC2018 已提交
4528

C
CyC2018 已提交
4529
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
C
CyC2018 已提交
4530 4531
```

C
CyC2018 已提交
4532
路径和定义为从 root 到 leaf 的所有节点的和。
C
CyC2018 已提交
4533

C
CyC2018 已提交
4534
```java
C
CyC2018 已提交
4535 4536 4537 4538
public boolean hasPathSum(TreeNode root, int sum) {
    if (root == null) return false;
    if (root.left == null && root.right == null && root.val == sum) return true;
    return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
C
CyC2018 已提交
4539 4540
}
```
C
CyC2018 已提交
4541

C
CyC2018 已提交
4542
**统计路径和等于一个数的路径数量** 
C
CyC2018 已提交
4543

C
CyC2018 已提交
4544
[437. Path Sum III (Easy)](https://leetcode.com/problems/path-sum-iii/description/)
C
CyC2018 已提交
4545

C
CyC2018 已提交
4546
```html
C
CyC2018 已提交
4547
root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8
C
CyC2018 已提交
4548

C
CyC2018 已提交
4549 4550 4551 4552 4553 4554 4555
      10
     /  \
    5   -3
   / \    \
  3   2   11
 / \   \
3  -2   1
C
CyC2018 已提交
4556

C
CyC2018 已提交
4557
Return 3. The paths that sum to 8 are:
C
CyC2018 已提交
4558

C
CyC2018 已提交
4559 4560 4561
1.  5 -> 3
2.  5 -> 2 -> 1
3. -3 -> 11
C
CyC2018 已提交
4562
```
C
CyC2018 已提交
4563

C
CyC2018 已提交
4564
路径不一定以 root 开头,也不一定以 leaf 结尾,但是必须连续。
C
CyC2018 已提交
4565

C
CyC2018 已提交
4566
```java
C
CyC2018 已提交
4567 4568 4569 4570
public int pathSum(TreeNode root, int sum) {
    if (root == null) return 0;
    int ret = pathSumStartWithRoot(root, sum) + pathSum(root.left, sum) + pathSum(root.right, sum);
    return ret;
C
CyC2018 已提交
4571
}
C
CyC2018 已提交
4572

C
CyC2018 已提交
4573 4574 4575 4576 4577 4578
private int pathSumStartWithRoot(TreeNode root, int sum) {
    if (root == null) return 0;
    int ret = 0;
    if (root.val == sum) ret++;
    ret += pathSumStartWithRoot(root.left, sum - root.val) + pathSumStartWithRoot(root.right, sum - root.val);
    return ret;
C
CyC2018 已提交
4579 4580
}
```
C
CyC2018 已提交
4581

C
CyC2018 已提交
4582
**子树** 
C
CyC2018 已提交
4583

C
CyC2018 已提交
4584
[572. Subtree of Another Tree (Easy)](https://leetcode.com/problems/subtree-of-another-tree/description/)
C
CyC2018 已提交
4585 4586

```html
C
CyC2018 已提交
4587 4588 4589 4590 4591 4592
Given tree s:
     3
    / \
   4   5
  / \
 1   2
C
CyC2018 已提交
4593

C
CyC2018 已提交
4594 4595 4596 4597
Given tree t:
   4
  / \
 1   2
C
CyC2018 已提交
4598

C
CyC2018 已提交
4599
Return true, because t has the same structure and node values with a subtree of s.
C
CyC2018 已提交
4600

C
CyC2018 已提交
4601
Given tree s:
C
CyC2018 已提交
4602

C
CyC2018 已提交
4603 4604 4605 4606 4607 4608 4609
     3
    / \
   4   5
  / \
 1   2
    /
   0
C
CyC2018 已提交
4610

C
CyC2018 已提交
4611 4612 4613 4614
Given tree t:
   4
  / \
 1   2
C
CyC2018 已提交
4615

C
CyC2018 已提交
4616
Return false.
C
CyC2018 已提交
4617 4618 4619
```

```java
C
CyC2018 已提交
4620 4621 4622
public boolean isSubtree(TreeNode s, TreeNode t) {
    if (s == null) return false;
    return isSubtreeWithRoot(s, t) || isSubtree(s.left, t) || isSubtree(s.right, t);
C
CyC2018 已提交
4623 4624
}

C
CyC2018 已提交
4625 4626 4627 4628 4629
private boolean isSubtreeWithRoot(TreeNode s, TreeNode t) {
    if (t == null && s == null) return true;
    if (t == null || s == null) return false;
    if (t.val != s.val) return false;
    return isSubtreeWithRoot(s.left, t.left) && isSubtreeWithRoot(s.right, t.right);
C
CyC2018 已提交
4630 4631 4632
}
```

C
CyC2018 已提交
4633
**树的对称** 
C
CyC2018 已提交
4634

C
CyC2018 已提交
4635
[101. Symmetric Tree (Easy)](https://leetcode.com/problems/symmetric-tree/description/)
C
CyC2018 已提交
4636 4637

```html
C
CyC2018 已提交
4638 4639 4640 4641 4642
    1
   / \
  2   2
 / \ / \
3  4 4  3
C
CyC2018 已提交
4643 4644 4645
```

```java
C
CyC2018 已提交
4646 4647 4648
public boolean isSymmetric(TreeNode root) {
    if (root == null) return true;
    return isSymmetric(root.left, root.right);
C
CyC2018 已提交
4649 4650
}

C
CyC2018 已提交
4651 4652 4653 4654 4655
private boolean isSymmetric(TreeNode t1, TreeNode t2) {
    if (t1 == null && t2 == null) return true;
    if (t1 == null || t2 == null) return false;
    if (t1.val != t2.val) return false;
    return isSymmetric(t1.left, t2.right) && isSymmetric(t1.right, t2.left);
C
CyC2018 已提交
4656 4657 4658
}
```

C
CyC2018 已提交
4659
**最小路径** 
C
CyC2018 已提交
4660

C
CyC2018 已提交
4661
[111. Minimum Depth of Binary Tree (Easy)](https://leetcode.com/problems/minimum-depth-of-binary-tree/description/)
C
CyC2018 已提交
4662 4663

树的根节点到叶子节点的最小路径长度
C
CyC2018 已提交
4664 4665

```java
C
CyC2018 已提交
4666 4667 4668 4669 4670 4671
public int minDepth(TreeNode root) {
    if (root == null) return 0;
    int left = minDepth(root.left);
    int right = minDepth(root.right);
    if (left == 0 || right == 0) return left + right + 1;
    return Math.min(left, right) + 1;
C
CyC2018 已提交
4672 4673 4674
}
```

C
CyC2018 已提交
4675
**统计左叶子节点的和** 
C
CyC2018 已提交
4676

C
CyC2018 已提交
4677
[404. Sum of Left Leaves (Easy)](https://leetcode.com/problems/sum-of-left-leaves/description/)
C
CyC2018 已提交
4678 4679

```html
C
CyC2018 已提交
4680 4681 4682 4683 4684
    3
   / \
  9  20
    /  \
   15   7
C
CyC2018 已提交
4685

C
CyC2018 已提交
4686
There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.
C
CyC2018 已提交
4687 4688 4689
```

```java
C
CyC2018 已提交
4690 4691 4692 4693
public int sumOfLeftLeaves(TreeNode root) {
    if (root == null) return 0;
    if (isLeaf(root.left)) return root.left.val + sumOfLeftLeaves(root.right);
    return sumOfLeftLeaves(root.left) + sumOfLeftLeaves(root.right);
C
CyC2018 已提交
4694 4695
}

C
CyC2018 已提交
4696 4697 4698
private boolean isLeaf(TreeNode node){
    if (node == null) return false;
    return node.left == null && node.right == null;
C
CyC2018 已提交
4699 4700 4701
}
```

C
CyC2018 已提交
4702
**相同节点值的最大路径长度** 
C
CyC2018 已提交
4703

C
CyC2018 已提交
4704
[687. Longest Univalue Path (Easy)](https://leetcode.com/problems/longest-univalue-path/)
C
CyC2018 已提交
4705

C
CyC2018 已提交
4706
```html
C
CyC2018 已提交
4707 4708 4709 4710 4711
             1
            / \
           4   5
          / \   \
         4   4   5
C
CyC2018 已提交
4712

C
CyC2018 已提交
4713
Output : 2
C
CyC2018 已提交
4714
```
C
CyC2018 已提交
4715 4716

```java
C
CyC2018 已提交
4717
private int path = 0;
C
CyC2018 已提交
4718

C
CyC2018 已提交
4719 4720 4721
public int longestUnivaluePath(TreeNode root) {
    dfs(root);
    return path;
C
CyC2018 已提交
4722
}
C
CyC2018 已提交
4723

C
CyC2018 已提交
4724 4725 4726 4727 4728 4729 4730 4731
private int dfs(TreeNode root){
    if (root == null) return 0;
    int left = dfs(root.left);
    int right = dfs(root.right);
    int leftPath = root.left != null && root.left.val == root.val ? left + 1 : 0;
    int rightPath = root.right != null && root.right.val == root.val ? right + 1 : 0;
    path = Math.max(path, leftPath + rightPath);
    return Math.max(leftPath, rightPath);
C
CyC2018 已提交
4732 4733 4734
}
```

C
CyC2018 已提交
4735
**间隔遍历** 
C
CyC2018 已提交
4736

C
CyC2018 已提交
4737
[337. House Robber III (Medium)](https://leetcode.com/problems/house-robber-iii/description/)
C
CyC2018 已提交
4738 4739

```html
C
CyC2018 已提交
4740 4741 4742 4743 4744 4745
     3
    / \
   2   3
    \   \
     3   1
Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.
C
CyC2018 已提交
4746 4747 4748
```

```java
C
CyC2018 已提交
4749 4750 4751 4752 4753 4754 4755
public int rob(TreeNode root) {
    if (root == null) return 0;
    int val1 = root.val;
    if (root.left != null) val1 += rob(root.left.left) + rob(root.left.right);
    if (root.right != null) val1 += rob(root.right.left) + rob(root.right.right);
    int val2 = rob(root.left) + rob(root.right);
    return Math.max(val1, val2);
C
CyC2018 已提交
4756 4757 4758
}
```

C
CyC2018 已提交
4759
**找出二叉树中第二小的节点** 
C
CyC2018 已提交
4760

C
CyC2018 已提交
4761
[671. Second Minimum Node In a Binary Tree (Easy)](https://leetcode.com/problems/second-minimum-node-in-a-binary-tree/description/)
C
CyC2018 已提交
4762 4763 4764

```html
Input:
C
CyC2018 已提交
4765 4766 4767 4768 4769
   2
  / \
 2   5
    / \
    5  7
C
CyC2018 已提交
4770

C
CyC2018 已提交
4771
Output: 5
C
CyC2018 已提交
4772 4773
```

C
CyC2018 已提交
4774
一个节点要么具有 0 个或 2 个子节点,如果有子节点,那么根节点是最小的节点。
C
CyC2018 已提交
4775

C
CyC2018 已提交
4776
```java
C
CyC2018 已提交
4777 4778 4779 4780 4781 4782 4783 4784 4785 4786
public int findSecondMinimumValue(TreeNode root) {
    if (root == null) return -1;
    if (root.left == null && root.right == null) return -1;
    int leftVal = root.left.val;
    int rightVal = root.right.val;
    if (leftVal == root.val) leftVal = findSecondMinimumValue(root.left);
    if (rightVal == root.val) rightVal = findSecondMinimumValue(root.right);
    if (leftVal != -1 && rightVal != -1) return Math.min(leftVal, rightVal);
    if (leftVal != -1) return leftVal;
    return rightVal;
C
CyC2018 已提交
4787 4788
}
```
C
CyC2018 已提交
4789

C
CyC2018 已提交
4790
### 层次遍历
C
CyC2018 已提交
4791

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

C
CyC2018 已提交
4794
**一棵树每层节点的平均数** 
C
CyC2018 已提交
4795

C
CyC2018 已提交
4796
[637. Average of Levels in Binary Tree (Easy)](https://leetcode.com/problems/average-of-levels-in-binary-tree/description/)
C
CyC2018 已提交
4797 4798

```java
C
CyC2018 已提交
4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815
public List<Double> averageOfLevels(TreeNode root) {
    List<Double> ret = new ArrayList<>();
    if (root == null) return ret;
    Queue<TreeNode> queue = new LinkedList<>();
    queue.add(root);
    while (!queue.isEmpty()) {
        int cnt = queue.size();
        double sum = 0;
        for (int i = 0; i < cnt; i++) {
            TreeNode node = queue.poll();
            sum += node.val;
            if (node.left != null) queue.add(node.left);
            if (node.right != null) queue.add(node.right);
        }
        ret.add(sum / cnt);
    }
    return ret;
C
CyC2018 已提交
4816 4817 4818
}
```

C
CyC2018 已提交
4819
**得到左下角的节点** 
C
CyC2018 已提交
4820

C
CyC2018 已提交
4821
[513. Find Bottom Left Tree Value (Easy)](https://leetcode.com/problems/find-bottom-left-tree-value/description/)
C
CyC2018 已提交
4822

C
CyC2018 已提交
4823 4824
```html
Input:
C
CyC2018 已提交
4825

C
CyC2018 已提交
4826 4827 4828 4829 4830 4831 4832
        1
       / \
      2   3
     /   / \
    4   5   6
       /
      7
C
CyC2018 已提交
4833 4834 4835 4836 4837 4838

Output:
7
```

```java
C
CyC2018 已提交
4839 4840 4841 4842 4843 4844 4845 4846 4847
public int findBottomLeftValue(TreeNode root) {
    Queue<TreeNode> queue = new LinkedList<>();
    queue.add(root);
    while (!queue.isEmpty()) {
        root = queue.poll();
        if (root.right != null) queue.add(root.right);
        if (root.left != null) queue.add(root.left);
    }
    return root.val;
C
CyC2018 已提交
4848 4849 4850
}
```

C
CyC2018 已提交
4851
### 前中后序遍历
C
CyC2018 已提交
4852 4853

```html
C
CyC2018 已提交
4854 4855 4856 4857 4858
    1
   / \
  2   3
 / \   \
4   5   6
C
CyC2018 已提交
4859 4860
```

C
CyC2018 已提交
4861 4862 4863 4864
- 层次遍历顺序:[1 2 3 4 5 6]
- 前序遍历顺序:[1 2 4 5 3 6]
- 中序遍历顺序:[4 2 5 1 3 6]
- 后序遍历顺序:[4 5 2 6 3 1]
C
CyC2018 已提交
4865

C
CyC2018 已提交
4866
层次遍历使用 BFS 实现,利用的就是 BFS 一层一层遍历的特性;而前序、中序、后序遍历利用了 DFS 实现。
C
CyC2018 已提交
4867 4868 4869

前序、中序、后序遍只是在对节点访问的顺序有一点不同,其它都相同。

C
CyC2018 已提交
4870
① 前序
C
CyC2018 已提交
4871 4872

```java
C
CyC2018 已提交
4873 4874 4875 4876
void dfs(TreeNode root) {
    visit(root);
    dfs(root.left);
    dfs(root.right);
C
CyC2018 已提交
4877 4878 4879
}
```

C
CyC2018 已提交
4880
② 中序
C
CyC2018 已提交
4881

C
CyC2018 已提交
4882
```java
C
CyC2018 已提交
4883 4884 4885 4886
void dfs(TreeNode root) {
    dfs(root.left);
    visit(root);
    dfs(root.right);
C
CyC2018 已提交
4887
}
C
CyC2018 已提交
4888 4889
```

C
CyC2018 已提交
4890
③ 后序
C
CyC2018 已提交
4891 4892

```java
C
CyC2018 已提交
4893 4894 4895 4896
void dfs(TreeNode root) {
    dfs(root.left);
    dfs(root.right);
    visit(root);
C
CyC2018 已提交
4897 4898 4899
}
```

C
CyC2018 已提交
4900
**非递归实现二叉树的前序遍历** 
C
CyC2018 已提交
4901

C
CyC2018 已提交
4902
[144. Binary Tree Preorder Traversal (Medium)](https://leetcode.com/problems/binary-tree-preorder-traversal/description/)
C
CyC2018 已提交
4903 4904

```java
C
CyC2018 已提交
4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916
public List<Integer> preorderTraversal(TreeNode root) {
    List<Integer> ret = new ArrayList<>();
    Stack<TreeNode> stack = new Stack<>();
    stack.push(root);
    while (!stack.isEmpty()) {
        TreeNode node = stack.pop();
        if (node == null) continue;
        ret.add(node.val);
        stack.push(node.right);  // 先右后左,保证左子树先遍历
        stack.push(node.left);
    }
    return ret;
C
CyC2018 已提交
4917 4918 4919
}
```

C
CyC2018 已提交
4920
**非递归实现二叉树的后序遍历** 
C
CyC2018 已提交
4921

C
CyC2018 已提交
4922
[145. Binary Tree Postorder Traversal (Medium)](https://leetcode.com/problems/binary-tree-postorder-traversal/description/)
C
CyC2018 已提交
4923

C
CyC2018 已提交
4924
前序遍历为 root -> left -> right,后序遍历为 left -> right -> root。可以修改前序遍历成为 root -> right -> left,那么这个顺序就和后序遍历正好相反。
C
CyC2018 已提交
4925 4926

```java
C
CyC2018 已提交
4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939
public List<Integer> postorderTraversal(TreeNode root) {
    List<Integer> ret = new ArrayList<>();
    Stack<TreeNode> stack = new Stack<>();
    stack.push(root);
    while (!stack.isEmpty()) {
        TreeNode node = stack.pop();
        if (node == null) continue;
        ret.add(node.val);
        stack.push(node.left);
        stack.push(node.right);
    }
    Collections.reverse(ret);
    return ret;
C
CyC2018 已提交
4940 4941 4942
}
```

C
CyC2018 已提交
4943
**非递归实现二叉树的中序遍历** 
C
CyC2018 已提交
4944

C
CyC2018 已提交
4945
[94. Binary Tree Inorder Traversal (Medium)](https://leetcode.com/problems/binary-tree-inorder-traversal/description/)
C
CyC2018 已提交
4946 4947

```java
C
CyC2018 已提交
4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962
public List<Integer> inorderTraversal(TreeNode root) {
    List<Integer> ret = new ArrayList<>();
    if (root == null) return ret;
    Stack<TreeNode> stack = new Stack<>();
    TreeNode cur = root;
    while (cur != null || !stack.isEmpty()) {
        while (cur != null) {
            stack.push(cur);
            cur = cur.left;
        }
        TreeNode node = stack.pop();
        ret.add(node.val);
        cur = node.right;
    }
    return ret;
C
CyC2018 已提交
4963 4964 4965
}
```

C
CyC2018 已提交
4966
### BST
C
CyC2018 已提交
4967

C
CyC2018 已提交
4968
二叉查找树(BST):根节点大于等于左子树所有节点,小于等于右子树所有节点。
C
CyC2018 已提交
4969

C
CyC2018 已提交
4970
二叉查找树中序遍历有序。
C
CyC2018 已提交
4971

C
CyC2018 已提交
4972
**修剪二叉查找树** 
C
CyC2018 已提交
4973

C
CyC2018 已提交
4974
[669. Trim a Binary Search Tree (Easy)](https://leetcode.com/problems/trim-a-binary-search-tree/description/)
C
CyC2018 已提交
4975 4976

```html
C
CyC2018 已提交
4977
Input:
C
CyC2018 已提交
4978

C
CyC2018 已提交
4979 4980 4981 4982 4983 4984 4985
    3
   / \
  0   4
   \
    2
   /
  1
C
CyC2018 已提交
4986

C
CyC2018 已提交
4987 4988
  L = 1
  R = 3
C
CyC2018 已提交
4989

C
CyC2018 已提交
4990 4991
Output:

C
CyC2018 已提交
4992 4993 4994 4995 4996
      3
     /
   2
  /
 1
C
CyC2018 已提交
4997 4998
```

C
CyC2018 已提交
4999
题目描述:只保留值在 L \~ R 之间的节点
C
CyC2018 已提交
5000 5001

```java
C
CyC2018 已提交
5002 5003 5004 5005 5006 5007 5008
public TreeNode trimBST(TreeNode root, int L, int R) {
    if (root == null) return null;
    if (root.val > R) return trimBST(root.left, L, R);
    if (root.val < L) return trimBST(root.right, L, R);
    root.left = trimBST(root.left, L, R);
    root.right = trimBST(root.right, L, R);
    return root;
C
CyC2018 已提交
5009 5010 5011
}
```

C
CyC2018 已提交
5012
**寻找二叉查找树的第 k 个元素** 
C
CyC2018 已提交
5013

C
CyC2018 已提交
5014
[230. Kth Smallest Element in a BST (Medium)](https://leetcode.com/problems/kth-smallest-element-in-a-bst/description/)
C
CyC2018 已提交
5015 5016


C
CyC2018 已提交
5017
中序遍历解法:
C
CyC2018 已提交
5018 5019

```java
C
CyC2018 已提交
5020 5021
private int cnt = 0;
private int val;
C
CyC2018 已提交
5022

C
CyC2018 已提交
5023 5024 5025
public int kthSmallest(TreeNode root, int k) {
    inOrder(root, k);
    return val;
C
CyC2018 已提交
5026
}
C
CyC2018 已提交
5027

C
CyC2018 已提交
5028 5029 5030 5031 5032 5033 5034 5035 5036
private void inOrder(TreeNode node, int k) {
    if (node == null) return;
    inOrder(node.left, k);
    cnt++;
    if (cnt == k) {
        val = node.val;
        return;
    }
    inOrder(node.right, k);
C
CyC2018 已提交
5037 5038 5039
}
```

C
CyC2018 已提交
5040
递归解法:
C
CyC2018 已提交
5041 5042

```java
C
CyC2018 已提交
5043 5044 5045 5046 5047
public int kthSmallest(TreeNode root, int k) {
    int leftCnt = count(root.left);
    if (leftCnt == k - 1) return root.val;
    if (leftCnt > k - 1) return kthSmallest(root.left, k);
    return kthSmallest(root.right, k - leftCnt - 1);
C
CyC2018 已提交
5048 5049
}

C
CyC2018 已提交
5050 5051 5052
private int count(TreeNode node) {
    if (node == null) return 0;
    return 1 + count(node.left) + count(node.right);
C
CyC2018 已提交
5053 5054 5055
}
```

C
CyC2018 已提交
5056
**把二叉查找树每个节点的值都加上比它大的节点的值** 
C
CyC2018 已提交
5057

C
CyC2018 已提交
5058
[Convert BST to Greater Tree (Easy)](https://leetcode.com/problems/convert-bst-to-greater-tree/description/)
C
CyC2018 已提交
5059 5060

```html
C
CyC2018 已提交
5061
Input: The root of a Binary Search Tree like this:
C
CyC2018 已提交
5062

C
CyC2018 已提交
5063 5064 5065
              5
            /   \
           2     13
C
CyC2018 已提交
5066

C
CyC2018 已提交
5067
Output: The root of a Greater Tree like this:
C
CyC2018 已提交
5068

C
CyC2018 已提交
5069 5070 5071
             18
            /   \
          20     13
C
CyC2018 已提交
5072 5073
```

C
CyC2018 已提交
5074 5075
先遍历右子树。

C
CyC2018 已提交
5076
```java
C
CyC2018 已提交
5077
private int sum = 0;
C
CyC2018 已提交
5078

C
CyC2018 已提交
5079 5080 5081
public TreeNode convertBST(TreeNode root) {
    traver(root);
    return root;
C
CyC2018 已提交
5082 5083
}

C
CyC2018 已提交
5084 5085 5086 5087 5088 5089
private void traver(TreeNode node) {
    if (node == null) return;
    traver(node.right);
    sum += node.val;
    node.val = sum;
    traver(node.left);
C
CyC2018 已提交
5090 5091 5092
}
```

C
CyC2018 已提交
5093
**二叉查找树的最近公共祖先** 
C
CyC2018 已提交
5094

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

```html
C
CyC2018 已提交
5098 5099 5100 5101 5102 5103 5104
        _______6______
      /                \
  ___2__             ___8__
 /      \           /      \
0        4         7        9
        /  \
       3   5
C
CyC2018 已提交
5105

C
CyC2018 已提交
5106
For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. Another example is LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.
C
CyC2018 已提交
5107 5108 5109
```

```java
C
CyC2018 已提交
5110 5111 5112 5113
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
    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 已提交
5114 5115 5116
}
```

C
CyC2018 已提交
5117
**二叉树的最近公共祖先** 
C
CyC2018 已提交
5118

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

```html
C
CyC2018 已提交
5122 5123 5124 5125 5126 5127 5128
       _______3______
      /              \
  ___5__           ___1__
 /      \         /      \
6        2       0        8
        /  \
       7    4
C
CyC2018 已提交
5129

C
CyC2018 已提交
5130
For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3. Another example is LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.
C
CyC2018 已提交
5131
```
C
CyC2018 已提交
5132

C
CyC2018 已提交
5133
```java
C
CyC2018 已提交
5134 5135 5136 5137 5138
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;
C
CyC2018 已提交
5139 5140 5141
}
```

C
CyC2018 已提交
5142
**从有序数组中构造二叉查找树** 
C
CyC2018 已提交
5143

C
CyC2018 已提交
5144
[108. Convert Sorted Array to Binary Search Tree (Easy)](https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/description/)
C
CyC2018 已提交
5145 5146

```java
C
CyC2018 已提交
5147 5148
public TreeNode sortedArrayToBST(int[] nums) {
    return toBST(nums, 0, nums.length - 1);
C
CyC2018 已提交
5149 5150
}

C
CyC2018 已提交
5151 5152 5153 5154 5155 5156 5157
private TreeNode toBST(int[] nums, int sIdx, int eIdx){
    if (sIdx > eIdx) return null;
    int mIdx = (sIdx + eIdx) / 2;
    TreeNode root = new TreeNode(nums[mIdx]);
    root.left =  toBST(nums, sIdx, mIdx - 1);
    root.right = toBST(nums, mIdx + 1, eIdx);
    return root;
C
CyC2018 已提交
5158 5159 5160
}
```

C
CyC2018 已提交
5161
**根据有序链表构造平衡的二叉查找树** 
C
CyC2018 已提交
5162

C
CyC2018 已提交
5163
[109. Convert Sorted List to Binary Search Tree (Medium)](https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/description/)
C
CyC2018 已提交
5164

C
CyC2018 已提交
5165
```html
C
CyC2018 已提交
5166
Given the sorted linked list: [-10,-3,0,5,9],
C
CyC2018 已提交
5167

C
CyC2018 已提交
5168
One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:
C
CyC2018 已提交
5169

C
CyC2018 已提交
5170 5171 5172 5173 5174
      0
     / \
   -3   9
   /   /
 -10  5
C
CyC2018 已提交
5175
```
C
CyC2018 已提交
5176 5177

```java
C
CyC2018 已提交
5178 5179 5180 5181 5182 5183 5184 5185 5186 5187
public TreeNode sortedListToBST(ListNode head) {
    if (head == null) return null;
    if (head.next == null) return new TreeNode(head.val);
    ListNode preMid = preMid(head);
    ListNode mid = preMid.next;
    preMid.next = null;  // 断开链表
    TreeNode t = new TreeNode(mid.val);
    t.left = sortedListToBST(head);
    t.right = sortedListToBST(mid.next);
    return t;
C
CyC2018 已提交
5188 5189
}

C
CyC2018 已提交
5190 5191 5192 5193 5194 5195 5196 5197 5198
private ListNode preMid(ListNode head) {
    ListNode slow = head, fast = head.next;
    ListNode pre = head;
    while (fast != null && fast.next != null) {
        pre = slow;
        slow = slow.next;
        fast = fast.next.next;
    }
    return pre;
C
CyC2018 已提交
5199
}
C
CyC2018 已提交
5200
```
C
CyC2018 已提交
5201

C
CyC2018 已提交
5202
**在二叉查找树中寻找两个节点,使它们的和为一个给定值** 
C
CyC2018 已提交
5203

C
CyC2018 已提交
5204
[653. Two Sum IV - Input is a BST (Easy)](https://leetcode.com/problems/two-sum-iv-input-is-a-bst/description/)
C
CyC2018 已提交
5205 5206 5207 5208

```html
Input:

C
CyC2018 已提交
5209 5210 5211 5212 5213
    5
   / \
  3   6
 / \   \
2   4   7
C
CyC2018 已提交
5214

C
CyC2018 已提交
5215
Target = 9
C
CyC2018 已提交
5216

C
CyC2018 已提交
5217
Output: True
C
CyC2018 已提交
5218 5219 5220 5221 5222 5223 5224
```

使用中序遍历得到有序数组之后,再利用双指针对数组进行查找。

应该注意到,这一题不能用分别在左右子树两部分来处理这种思想,因为两个待求的节点可能分别在左右子树中。

```java
C
CyC2018 已提交
5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235
public boolean findTarget(TreeNode root, int k) {
    List<Integer> nums = new ArrayList<>();
    inOrder(root, nums);
    int i = 0, j = nums.size() - 1;
    while (i < j) {
        int sum = nums.get(i) + nums.get(j);
        if (sum == k) return true;
        if (sum < k) i++;
        else j--;
    }
    return false;
C
CyC2018 已提交
5236 5237
}

C
CyC2018 已提交
5238 5239 5240 5241 5242
private void inOrder(TreeNode root, List<Integer> nums) {
    if (root == null) return;
    inOrder(root.left, nums);
    nums.add(root.val);
    inOrder(root.right, nums);
C
CyC2018 已提交
5243 5244 5245
}
```

C
CyC2018 已提交
5246
**在二叉查找树中查找两个节点之差的最小绝对值** 
C
CyC2018 已提交
5247

C
CyC2018 已提交
5248
[530. Minimum Absolute Difference in BST (Easy)](https://leetcode.com/problems/minimum-absolute-difference-in-bst/description/)
C
CyC2018 已提交
5249 5250 5251

```html
Input:
C
CyC2018 已提交
5252

C
CyC2018 已提交
5253 5254 5255 5256 5257
   1
    \
     3
    /
   2
C
CyC2018 已提交
5258 5259 5260 5261

Output:

1
C
CyC2018 已提交
5262 5263
```

C
CyC2018 已提交
5264
利用二叉查找树的中序遍历为有序的性质,计算中序遍历中临近的两个节点之差的绝对值,取最小值。
C
CyC2018 已提交
5265 5266

```java
C
CyC2018 已提交
5267 5268
private int minDiff = Integer.MAX_VALUE;
private TreeNode preNode = null;
C
CyC2018 已提交
5269

C
CyC2018 已提交
5270 5271 5272
public int getMinimumDifference(TreeNode root) {
    inOrder(root);
    return minDiff;
C
CyC2018 已提交
5273 5274
}

C
CyC2018 已提交
5275 5276 5277 5278 5279 5280
private void inOrder(TreeNode node) {
    if (node == null) return;
    inOrder(node.left);
    if (preNode != null) minDiff = Math.min(minDiff, node.val - preNode.val);
    preNode = node;
    inOrder(node.right);
C
CyC2018 已提交
5281 5282 5283
}
```

C
CyC2018 已提交
5284
**寻找二叉查找树中出现次数最多的值** 
C
CyC2018 已提交
5285

C
CyC2018 已提交
5286
[501. Find Mode in Binary Search Tree (Easy)](https://leetcode.com/problems/find-mode-in-binary-search-tree/description/)
C
CyC2018 已提交
5287 5288

```html
C
CyC2018 已提交
5289 5290 5291 5292 5293
   1
    \
     2
    /
   2
C
CyC2018 已提交
5294

C
CyC2018 已提交
5295
return [2].
C
CyC2018 已提交
5296 5297
```

C
CyC2018 已提交
5298 5299
答案可能不止一个,也就是有多个值出现的次数一样多。

C
CyC2018 已提交
5300
```java
C
CyC2018 已提交
5301 5302 5303
private int curCnt = 1;
private int maxCnt = 1;
private TreeNode preNode = null;
C
CyC2018 已提交
5304

C
CyC2018 已提交
5305 5306 5307 5308 5309 5310 5311 5312 5313
public int[] findMode(TreeNode root) {
    List<Integer> maxCntNums = new ArrayList<>();
    inOrder(root, maxCntNums);
    int[] ret = new int[maxCntNums.size()];
    int idx = 0;
    for (int num : maxCntNums) {
        ret[idx++] = num;
    }
    return ret;
C
CyC2018 已提交
5314 5315
}

C
CyC2018 已提交
5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331
private void inOrder(TreeNode node, List<Integer> nums) {
    if (node == null) return;
    inOrder(node.left, nums);
    if (preNode != null) {
        if (preNode.val == node.val) curCnt++;
        else curCnt = 1;
    }
    if (curCnt > maxCnt) {
        maxCnt = curCnt;
        nums.clear();
        nums.add(node.val);
    } else if (curCnt == maxCnt) {
        nums.add(node.val);
    }
    preNode = node;
    inOrder(node.right, nums);
C
CyC2018 已提交
5332 5333 5334
}
```

C
CyC2018 已提交
5335
### Trie
C
CyC2018 已提交
5336

C
CyC2018 已提交
5337
<div align="center"> <img src="pics/5c638d59-d4ae-4ba4-ad44-80bdc30f38dd.jpg"/> </div><br>
C
CyC2018 已提交
5338

C
CyC2018 已提交
5339
Trie,又称前缀树或字典树,用于判断字符串是否存在或者是否具有某种字符串前缀。
C
CyC2018 已提交
5340

C
CyC2018 已提交
5341
**实现一个 Trie** 
C
CyC2018 已提交
5342

C
CyC2018 已提交
5343
[208. Implement Trie (Prefix Tree) (Medium)](https://leetcode.com/problems/implement-trie-prefix-tree/description/)
C
CyC2018 已提交
5344 5345

```java
C
CyC2018 已提交
5346
class Trie {
C
CyC2018 已提交
5347

C
CyC2018 已提交
5348 5349 5350 5351
    private class Node {
        Node[] childs = new Node[26];
        boolean isLeaf;
    }
C
CyC2018 已提交
5352

C
CyC2018 已提交
5353
    private Node root = new Node();
C
CyC2018 已提交
5354

C
CyC2018 已提交
5355 5356
    public Trie() {
    }
C
CyC2018 已提交
5357

C
CyC2018 已提交
5358 5359 5360
    public void insert(String word) {
        insert(word, root);
    }
C
CyC2018 已提交
5361

C
CyC2018 已提交
5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373
    private void insert(String word, Node node) {
        if (node == null) return;
        if (word.length() == 0) {
            node.isLeaf = true;
            return;
        }
        int index = indexForChar(word.charAt(0));
        if (node.childs[index] == null) {
            node.childs[index] = new Node();
        }
        insert(word.substring(1), node.childs[index]);
    }
C
CyC2018 已提交
5374

C
CyC2018 已提交
5375 5376 5377
    public boolean search(String word) {
        return search(word, root);
    }
C
CyC2018 已提交
5378

C
CyC2018 已提交
5379 5380 5381 5382 5383 5384
    private boolean search(String word, Node node) {
        if (node == null) return false;
        if (word.length() == 0) return node.isLeaf;
        int index = indexForChar(word.charAt(0));
        return search(word.substring(1), node.childs[index]);
    }
C
CyC2018 已提交
5385

C
CyC2018 已提交
5386 5387 5388
    public boolean startsWith(String prefix) {
        return startWith(prefix, root);
    }
C
CyC2018 已提交
5389

C
CyC2018 已提交
5390 5391 5392 5393 5394 5395
    private boolean startWith(String prefix, Node node) {
        if (node == null) return false;
        if (prefix.length() == 0) return true;
        int index = indexForChar(prefix.charAt(0));
        return startWith(prefix.substring(1), node.childs[index]);
    }
C
CyC2018 已提交
5396

C
CyC2018 已提交
5397 5398 5399
    private int indexForChar(char c) {
        return c - 'a';
    }
C
CyC2018 已提交
5400 5401 5402
}
```

C
CyC2018 已提交
5403
**实现一个 Trie,用来求前缀和** 
C
CyC2018 已提交
5404

C
CyC2018 已提交
5405
[677. Map Sum Pairs (Medium)](https://leetcode.com/problems/map-sum-pairs/description/)
C
CyC2018 已提交
5406 5407

```html
C
CyC2018 已提交
5408 5409 5410 5411
Input: insert("apple", 3), Output: Null
Input: sum("ap"), Output: 3
Input: insert("app", 2), Output: Null
Input: sum("ap"), Output: 5
C
CyC2018 已提交
5412 5413 5414
```

```java
C
CyC2018 已提交
5415
class MapSum {
C
CyC2018 已提交
5416

C
CyC2018 已提交
5417 5418 5419 5420
    private class Node {
        Node[] child = new Node[26];
        int value;
    }
C
CyC2018 已提交
5421

C
CyC2018 已提交
5422
    private Node root = new Node();
C
CyC2018 已提交
5423

C
CyC2018 已提交
5424
    public MapSum() {
C
CyC2018 已提交
5425

C
CyC2018 已提交
5426
    }
C
CyC2018 已提交
5427

C
CyC2018 已提交
5428 5429 5430
    public void insert(String key, int val) {
        insert(key, root, val);
    }
C
CyC2018 已提交
5431

C
CyC2018 已提交
5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443
    private void insert(String key, Node node, int val) {
        if (node == null) return;
        if (key.length() == 0) {
            node.value = val;
            return;
        }
        int index = indexForChar(key.charAt(0));
        if (node.child[index] == null) {
            node.child[index] = new Node();
        }
        insert(key.substring(1), node.child[index], val);
    }
C
CyC2018 已提交
5444

C
CyC2018 已提交
5445 5446 5447
    public int sum(String prefix) {
        return sum(prefix, root);
    }
C
CyC2018 已提交
5448

C
CyC2018 已提交
5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460
    private int sum(String prefix, Node node) {
        if (node == null) return 0;
        if (prefix.length() != 0) {
            int index = indexForChar(prefix.charAt(0));
            return sum(prefix.substring(1), node.child[index]);
        }
        int sum = node.value;
        for (Node child : node.child) {
            sum += sum(prefix, child);
        }
        return sum;
    }
C
CyC2018 已提交
5461

C
CyC2018 已提交
5462 5463 5464
    private int indexForChar(char c) {
        return c - 'a';
    }
C
CyC2018 已提交
5465 5466 5467 5468
}
```


C
CyC2018 已提交
5469
## 栈和队列
C
CyC2018 已提交
5470

C
CyC2018 已提交
5471
**用栈实现队列** 
C
CyC2018 已提交
5472

C
CyC2018 已提交
5473
[232. Implement Queue using Stacks (Easy)](https://leetcode.com/problems/implement-queue-using-stacks/description/)
C
CyC2018 已提交
5474

C
CyC2018 已提交
5475
栈的顺序为后进先出,而队列的顺序为先进先出。使用两个栈实现队列,一个元素需要经过两个栈才能出队列,在经过第一个栈时元素顺序被反转,经过第二个栈时再次被反转,此时就是先进先出顺序。
C
CyC2018 已提交
5476 5477

```java
C
CyC2018 已提交
5478
class MyQueue {
C
CyC2018 已提交
5479

C
CyC2018 已提交
5480 5481
    private Stack<Integer> in = new Stack<>();
    private Stack<Integer> out = new Stack<>();
C
CyC2018 已提交
5482

C
CyC2018 已提交
5483 5484 5485
    public void push(int x) {
        in.push(x);
    }
C
CyC2018 已提交
5486

C
CyC2018 已提交
5487 5488 5489 5490
    public int pop() {
        in2out();
        return out.pop();
    }
C
CyC2018 已提交
5491

C
CyC2018 已提交
5492 5493 5494 5495
    public int peek() {
        in2out();
        return out.peek();
    }
C
CyC2018 已提交
5496

C
CyC2018 已提交
5497 5498 5499 5500 5501 5502 5503
    private void in2out() {
        if (out.isEmpty()) {
            while (!in.isEmpty()) {
                out.push(in.pop());
            }
        }
    }
C
CyC2018 已提交
5504

C
CyC2018 已提交
5505 5506 5507
    public boolean empty() {
        return in.isEmpty() && out.isEmpty();
    }
C
CyC2018 已提交
5508 5509
}
```
C
CyC2018 已提交
5510

C
CyC2018 已提交
5511
**用队列实现栈** 
C
CyC2018 已提交
5512

C
CyC2018 已提交
5513
[225. Implement Stack using Queues (Easy)](https://leetcode.com/problems/implement-stack-using-queues/description/)
C
CyC2018 已提交
5514

C
CyC2018 已提交
5515
在将一个元素 x 插入队列时,为了维护原来的后进先出顺序,需要让 x 插入队列首部。而队列的默认插入顺序是队列尾部,因此在将 x 插入队列尾部之后,需要让除了 x 之外的所有元素出队列,再入队列。
C
CyC2018 已提交
5516 5517

```java
C
CyC2018 已提交
5518
class MyStack {
C
CyC2018 已提交
5519

C
CyC2018 已提交
5520
    private Queue<Integer> queue;
C
CyC2018 已提交
5521

C
CyC2018 已提交
5522 5523 5524
    public MyStack() {
        queue = new LinkedList<>();
    }
C
CyC2018 已提交
5525

C
CyC2018 已提交
5526 5527 5528 5529 5530 5531 5532
    public void push(int x) {
        queue.add(x);
        int cnt = queue.size();
        while (cnt-- > 1) {
            queue.add(queue.poll());
        }
    }
C
CyC2018 已提交
5533

C
CyC2018 已提交
5534 5535 5536
    public int pop() {
        return queue.remove();
    }
C
CyC2018 已提交
5537

C
CyC2018 已提交
5538 5539 5540
    public int top() {
        return queue.peek();
    }
C
CyC2018 已提交
5541

C
CyC2018 已提交
5542 5543 5544
    public boolean empty() {
        return queue.isEmpty();
    }
C
CyC2018 已提交
5545 5546
}
```
C
CyC2018 已提交
5547

C
CyC2018 已提交
5548
**最小值栈** 
C
CyC2018 已提交
5549

C
CyC2018 已提交
5550
[155. Min Stack (Easy)](https://leetcode.com/problems/min-stack/description/)
C
CyC2018 已提交
5551

C
CyC2018 已提交
5552
```java
C
CyC2018 已提交
5553
class MinStack {
C
CyC2018 已提交
5554

C
CyC2018 已提交
5555 5556 5557
    private Stack<Integer> dataStack;
    private Stack<Integer> minStack;
    private int min;
C
CyC2018 已提交
5558

C
CyC2018 已提交
5559 5560 5561 5562 5563
    public MinStack() {
        dataStack = new Stack<>();
        minStack = new Stack<>();
        min = Integer.MAX_VALUE;
    }
C
CyC2018 已提交
5564

C
CyC2018 已提交
5565 5566 5567 5568 5569
    public void push(int x) {
        dataStack.add(x);
        min = Math.min(min, x);
        minStack.add(min);
    }
C
CyC2018 已提交
5570

C
CyC2018 已提交
5571 5572 5573 5574 5575
    public void pop() {
        dataStack.pop();
        minStack.pop();
        min = minStack.isEmpty() ? Integer.MAX_VALUE : minStack.peek();
    }
C
CyC2018 已提交
5576

C
CyC2018 已提交
5577 5578 5579
    public int top() {
        return dataStack.peek();
    }
C
CyC2018 已提交
5580

C
CyC2018 已提交
5581 5582 5583
    public int getMin() {
        return minStack.peek();
    }
C
CyC2018 已提交
5584 5585 5586
}
```

C
CyC2018 已提交
5587
对于实现最小值队列问题,可以先将队列使用栈来实现,然后就将问题转换为最小值栈,这个问题出现在 编程之美:3.7。
C
CyC2018 已提交
5588

C
CyC2018 已提交
5589
**用栈实现括号匹配** 
C
CyC2018 已提交
5590

C
CyC2018 已提交
5591
[20. Valid Parentheses (Easy)](https://leetcode.com/problems/valid-parentheses/description/)
C
CyC2018 已提交
5592 5593

```html
C
CyC2018 已提交
5594 5595
"()[]{}"

C
CyC2018 已提交
5596
Output : true
C
CyC2018 已提交
5597 5598 5599
```

```java
C
CyC2018 已提交
5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618
public boolean isValid(String s) {
    Stack<Character> stack = new Stack<>();
    for (char c : s.toCharArray()) {
        if (c == '(' || c == '{' || c == '[') {
            stack.push(c);
        } else {
            if (stack.isEmpty()) {
                return false;
            }
            char cStack = stack.pop();
            boolean b1 = c == ')' && cStack != '(';
            boolean b2 = c == ']' && cStack != '[';
            boolean b3 = c == '}' && cStack != '{';
            if (b1 || b2 || b3) {
                return false;
            }
        }
    }
    return stack.isEmpty();
C
CyC2018 已提交
5619 5620 5621
}
```

C
CyC2018 已提交
5622
**数组中元素与下一个比它大的元素之间的距离** 
C
CyC2018 已提交
5623

C
CyC2018 已提交
5624
[739. Daily Temperatures (Medium)](https://leetcode.com/problems/daily-temperatures/description/)
C
CyC2018 已提交
5625

C
CyC2018 已提交
5626
```html
C
CyC2018 已提交
5627 5628
Input: [73, 74, 75, 71, 69, 72, 76, 73]
Output: [1, 1, 4, 2, 1, 1, 0, 0]
C
CyC2018 已提交
5629 5630 5631
```

在遍历数组时用栈把数组中的数存起来,如果当前遍历的数比栈顶元素来的大,说明栈顶元素的下一个比它大的数就是当前元素。
C
CyC2018 已提交
5632 5633

```java
C
CyC2018 已提交
5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645
public int[] dailyTemperatures(int[] temperatures) {
    int n = temperatures.length;
    int[] dist = new int[n];
    Stack<Integer> indexs = new Stack<>();
    for (int curIndex = 0; curIndex < n; curIndex++) {
        while (!indexs.isEmpty() && temperatures[curIndex] > temperatures[indexs.peek()]) {
            int preIndex = indexs.pop();
            dist[preIndex] = curIndex - preIndex;
        }
        indexs.add(curIndex);
    }
    return dist;
C
CyC2018 已提交
5646 5647 5648
}
```

C
CyC2018 已提交
5649
**循环数组中比当前元素大的下一个元素** 
C
CyC2018 已提交
5650

C
CyC2018 已提交
5651
[503. Next Greater Element II (Medium)](https://leetcode.com/problems/next-greater-element-ii/description/)
C
CyC2018 已提交
5652

C
CyC2018 已提交
5653
```text
C
CyC2018 已提交
5654 5655 5656 5657 5658
Input: [1,2,1]
Output: [2,-1,2]
Explanation: The first 1's next greater number is 2;
The number 2 can't find next greater number;
The second 1's next greater number needs to search circularly, which is also 2.
C
CyC2018 已提交
5659 5660
```

C
CyC2018 已提交
5661
与 739. Daily Temperatures (Medium) 不同的是,数组是循环数组,并且最后要求的不是距离而是下一个元素。
C
CyC2018 已提交
5662

C
CyC2018 已提交
5663
```java
C
CyC2018 已提交
5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678
public int[] nextGreaterElements(int[] nums) {
    int n = nums.length;
    int[] next = new int[n];
    Arrays.fill(next, -1);
    Stack<Integer> pre = new Stack<>();
    for (int i = 0; i < n * 2; i++) {
        int num = nums[i % n];
        while (!pre.isEmpty() && nums[pre.peek()] < num) {
            next[pre.pop()] = num;
        }
        if (i < n){
            pre.push(i);
        }
    }
    return next;
C
CyC2018 已提交
5679 5680 5681
}
```

C
CyC2018 已提交
5682
## 哈希表
C
CyC2018 已提交
5683

C
CyC2018 已提交
5684
哈希表使用 O(N) 空间复杂度存储数据,并且以 O(1) 时间复杂度求解问题。
C
CyC2018 已提交
5685

C
CyC2018 已提交
5686
- Java 中的  **HashSet**  用于存储一个集合,可以查找元素是否在集合中。如果元素有穷,并且范围不大,那么可以用一个布尔数组来存储一个元素是否存在。例如对于只有小写字符的元素,就可以用一个长度为 26 的布尔数组来存储一个字符集合,使得空间复杂度降低为 O(1)。
C
CyC2018 已提交
5687

C
CyC2018 已提交
5688
- Java 中的  **HashMap**  主要用于映射关系,从而把两个元素联系起来。HashMap 也可以用来对元素进行计数统计,此时键为元素,值为计数。和 HashSet 类似,如果元素有穷并且范围不大,可以用整型数组来进行统计。在对一个内容进行压缩或者其它转换时,利用 HashMap 可以把原始内容和转换后的内容联系起来。例如在一个简化 url 的系统中 [Leetcdoe : 535. Encode and Decode TinyURL (Medium)](https://leetcode.com/problems/encode-and-decode-tinyurl/description/),利用 HashMap 就可以存储精简后的 url 到原始 url 的映射,使得不仅可以显示简化的 url,也可以根据简化的 url 得到原始 url 从而定位到正确的资源。
C
CyC2018 已提交
5689

C
CyC2018 已提交
5690

C
CyC2018 已提交
5691
**数组中两个数的和为给定值** 
C
CyC2018 已提交
5692

C
CyC2018 已提交
5693
[1. Two Sum (Easy)](https://leetcode.com/problems/two-sum/description/)
C
CyC2018 已提交
5694

C
CyC2018 已提交
5695
可以先对数组进行排序,然后使用双指针方法或者二分查找方法。这样做的时间复杂度为 O(NlogN),空间复杂度为 O(1)。
C
CyC2018 已提交
5696

C
CyC2018 已提交
5697
用 HashMap 存储数组元素和索引的映射,在访问到 nums[i] 时,判断 HashMap 中是否存在 target - nums[i],如果存在说明 target - nums[i] 所在的索引和 i 就是要找的两个数。该方法的时间复杂度为 O(N),空间复杂度为 O(N),使用空间来换取时间。
C
CyC2018 已提交
5698 5699

```java
C
CyC2018 已提交
5700 5701 5702 5703 5704 5705 5706 5707 5708 5709
public int[] twoSum(int[] nums, int target) {
    HashMap<Integer, Integer> indexForNum = new HashMap<>();
    for (int i = 0; i < nums.length; i++) {
        if (indexForNum.containsKey(target - nums[i])) {
            return new int[]{indexForNum.get(target - nums[i]), i};
        } else {
            indexForNum.put(nums[i], i);
        }
    }
    return null;
C
CyC2018 已提交
5710 5711 5712
}
```

C
CyC2018 已提交
5713
**判断数组是否含有重复元素** 
C
CyC2018 已提交
5714

C
CyC2018 已提交
5715
[217. Contains Duplicate (Easy)](https://leetcode.com/problems/contains-duplicate/description/)
C
CyC2018 已提交
5716 5717

```java
C
CyC2018 已提交
5718 5719 5720 5721 5722 5723
public boolean containsDuplicate(int[] nums) {
    Set<Integer> set = new HashSet<>();
    for (int num : nums) {
        set.add(num);
    }
    return set.size() < nums.length;
C
CyC2018 已提交
5724 5725 5726
}
```

C
CyC2018 已提交
5727
**最长和谐序列** 
C
CyC2018 已提交
5728

C
CyC2018 已提交
5729
[594. Longest Harmonious Subsequence (Easy)](https://leetcode.com/problems/longest-harmonious-subsequence/description/)
C
CyC2018 已提交
5730 5731

```html
C
CyC2018 已提交
5732 5733 5734
Input: [1,3,2,2,5,2,3,7]
Output: 5
Explanation: The longest harmonious subsequence is [3,2,2,2,3].
C
CyC2018 已提交
5735 5736
```

C
CyC2018 已提交
5737
和谐序列中最大数和最小数之差正好为 1,应该注意的是序列的元素不一定是数组的连续元素。
C
CyC2018 已提交
5738 5739

```java
C
CyC2018 已提交
5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751
public int findLHS(int[] nums) {
    Map<Integer, Integer> countForNum = new HashMap<>();
    for (int num : nums) {
        countForNum.put(num, countForNum.getOrDefault(num, 0) + 1);
    }
    int longest = 0;
    for (int num : countForNum.keySet()) {
        if (countForNum.containsKey(num + 1)) {
            longest = Math.max(longest, countForNum.get(num + 1) + countForNum.get(num));
        }
    }
    return longest;
C
CyC2018 已提交
5752 5753 5754
}
```

C
CyC2018 已提交
5755
**最长连续序列** 
C
CyC2018 已提交
5756

C
CyC2018 已提交
5757
[128. Longest Consecutive Sequence (Hard)](https://leetcode.com/problems/longest-consecutive-sequence/description/)
C
CyC2018 已提交
5758

C
CyC2018 已提交
5759
```html
C
CyC2018 已提交
5760 5761
Given [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.
C
CyC2018 已提交
5762
```
C
CyC2018 已提交
5763

C
CyC2018 已提交
5764
要求以 O(N) 的时间复杂度求解。
C
CyC2018 已提交
5765 5766

```java
C
CyC2018 已提交
5767 5768 5769 5770 5771 5772 5773 5774 5775
public int longestConsecutive(int[] nums) {
    Map<Integer, Integer> countForNum = new HashMap<>();
    for (int num : nums) {
        countForNum.put(num, 1);
    }
    for (int num : nums) {
        forward(countForNum, num);
    }
    return maxCount(countForNum);
C
CyC2018 已提交
5776 5777
}

C
CyC2018 已提交
5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788
private int forward(Map<Integer, Integer> countForNum, int num) {
    if (!countForNum.containsKey(num)) {
        return 0;
    }
    int cnt = countForNum.get(num);
    if (cnt > 1) {
        return cnt;
    }
    cnt = forward(countForNum, num + 1) + 1;
    countForNum.put(num, cnt);
    return cnt;
C
CyC2018 已提交
5789 5790
}

C
CyC2018 已提交
5791 5792 5793 5794 5795 5796
private int maxCount(Map<Integer, Integer> countForNum) {
    int max = 0;
    for (int num : countForNum.keySet()) {
        max = Math.max(max, countForNum.get(num));
    }
    return max;
C
CyC2018 已提交
5797 5798 5799
}
```

C
CyC2018 已提交
5800
## 字符串
C
CyC2018 已提交
5801

C
CyC2018 已提交
5802
**字符串循环移位包含** 
C
CyC2018 已提交
5803

C
CyC2018 已提交
5804
[编程之美 3.1](#)
C
CyC2018 已提交
5805 5806

```html
C
CyC2018 已提交
5807 5808
s1 = AABCD, s2 = CDAA
Return : true
C
CyC2018 已提交
5809
```
C
CyC2018 已提交
5810

C
CyC2018 已提交
5811
给定两个字符串 s1 和 s2,要求判定 s2 是否能够被 s1 做循环移位得到的字符串包含。
C
CyC2018 已提交
5812

C
CyC2018 已提交
5813
s1 进行循环移位的结果是 s1s1 的子字符串,因此只要判断 s2 是否是 s1s1 的子字符串即可。
C
CyC2018 已提交
5814

C
CyC2018 已提交
5815
**字符串循环移位** 
C
CyC2018 已提交
5816

C
CyC2018 已提交
5817
[编程之美 2.17](#)
C
CyC2018 已提交
5818 5819

```html
C
CyC2018 已提交
5820 5821
s = "abcd123" k = 3
Return "123abcd"
C
CyC2018 已提交
5822 5823
```

C
CyC2018 已提交
5824
将字符串向右循环移动 k 位。
C
CyC2018 已提交
5825

C
CyC2018 已提交
5826
将 abcd123 中的 abcd 和 123 单独翻转,得到 dcba321,然后对整个字符串进行翻转,得到 123abcd。
C
CyC2018 已提交
5827

C
CyC2018 已提交
5828
**字符串中单词的翻转** 
C
CyC2018 已提交
5829

C
CyC2018 已提交
5830
[程序员代码面试指南](#)
C
CyC2018 已提交
5831

C
CyC2018 已提交
5832
```html
C
CyC2018 已提交
5833 5834
s = "I am a student"
Return "student a am I"
C
CyC2018 已提交
5835 5836
```

C
CyC2018 已提交
5837
将每个单词翻转,然后将整个字符串翻转。
C
CyC2018 已提交
5838

C
CyC2018 已提交
5839
**两个字符串包含的字符是否完全相同** 
C
CyC2018 已提交
5840

C
CyC2018 已提交
5841
[242. Valid Anagram (Easy)](https://leetcode.com/problems/valid-anagram/description/)
C
CyC2018 已提交
5842 5843

```html
C
CyC2018 已提交
5844 5845
s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return false.
C
CyC2018 已提交
5846 5847
```

C
CyC2018 已提交
5848
可以用 HashMap 来映射字符与出现次数,然后比较两个字符串出现的字符数量是否相同。
C
CyC2018 已提交
5849

C
CyC2018 已提交
5850
由于本题的字符串只包含 26 个小写字符,因此可以使用长度为 26 的整型数组对字符串出现的字符进行统计,不再使用 HashMap。
C
CyC2018 已提交
5851 5852

```java
C
CyC2018 已提交
5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866
public boolean isAnagram(String s, String t) {
    int[] cnts = new int[26];
    for (char c : s.toCharArray()) {
        cnts[c - 'a']++;
    }
    for (char c : t.toCharArray()) {
        cnts[c - 'a']--;
    }
    for (int cnt : cnts) {
        if (cnt != 0) {
            return false;
        }
    }
    return true;
C
CyC2018 已提交
5867 5868 5869
}
```

C
CyC2018 已提交
5870
**计算一组字符集合可以组成的回文字符串的最大长度** 
C
CyC2018 已提交
5871

C
CyC2018 已提交
5872
[409. Longest Palindrome (Easy)](https://leetcode.com/problems/longest-palindrome/description/)
C
CyC2018 已提交
5873 5874

```html
C
CyC2018 已提交
5875 5876 5877
Input : "abccccdd"
Output : 7
Explanation : One longest palindrome that can be built is "dccaccd", whose length is 7.
C
CyC2018 已提交
5878 5879
```

C
CyC2018 已提交
5880
使用长度为 256 的整型数组来统计每个字符出现的个数,每个字符有偶数个可以用来构成回文字符串。
C
CyC2018 已提交
5881 5882

因为回文字符串最中间的那个字符可以单独出现,所以如果有单独的字符就把它放到最中间。
C
CyC2018 已提交
5883 5884

```java
C
CyC2018 已提交
5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897
public int longestPalindrome(String s) {
    int[] cnts = new int[256];
    for (char c : s.toCharArray()) {
        cnts[c]++;
    }
    int palindrome = 0;
    for (int cnt : cnts) {
        palindrome += (cnt / 2) * 2;
    }
    if (palindrome < s.length()) {
        palindrome++;   // 这个条件下 s 中一定有单个未使用的字符存在,可以把这个字符放到回文的最中间
    }
    return palindrome;
C
CyC2018 已提交
5898 5899 5900
}
```

C
CyC2018 已提交
5901
**字符串同构** 
C
CyC2018 已提交
5902

C
CyC2018 已提交
5903
[205. Isomorphic Strings (Easy)](https://leetcode.com/problems/isomorphic-strings/description/)
C
CyC2018 已提交
5904

C
CyC2018 已提交
5905
```html
C
CyC2018 已提交
5906 5907 5908
Given "egg", "add", return true.
Given "foo", "bar", return false.
Given "paper", "title", return true.
C
CyC2018 已提交
5909 5910
```

C
CyC2018 已提交
5911
记录一个字符上次出现的位置,如果两个字符串中的字符上次出现的位置一样,那么就属于同构。
C
CyC2018 已提交
5912 5913

```java
C
CyC2018 已提交
5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925
public boolean isIsomorphic(String s, String t) {
    int[] preIndexOfS = new int[256];
    int[] preIndexOfT = new int[256];
    for (int i = 0; i < s.length(); i++) {
        char sc = s.charAt(i), tc = t.charAt(i);
        if (preIndexOfS[sc] != preIndexOfT[tc]) {
            return false;
        }
        preIndexOfS[sc] = i + 1;
        preIndexOfT[tc] = i + 1;
    }
    return true;
C
CyC2018 已提交
5926 5927 5928
}
```

C
CyC2018 已提交
5929
**回文子字符串个数** 
C
CyC2018 已提交
5930

C
CyC2018 已提交
5931
[647. Palindromic Substrings (Medium)](https://leetcode.com/problems/palindromic-substrings/description/)
C
CyC2018 已提交
5932

C
CyC2018 已提交
5933
```html
C
CyC2018 已提交
5934 5935 5936
Input: "aaa"
Output: 6
Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".
C
CyC2018 已提交
5937
```
C
CyC2018 已提交
5938

C
CyC2018 已提交
5939
从字符串的某一位开始,尝试着去扩展子字符串。
C
CyC2018 已提交
5940

C
CyC2018 已提交
5941
```java
C
CyC2018 已提交
5942
private int cnt = 0;
C
CyC2018 已提交
5943

C
CyC2018 已提交
5944 5945 5946 5947 5948 5949
public int countSubstrings(String s) {
    for (int i = 0; i < s.length(); i++) {
        extendSubstrings(s, i, i);     // 奇数长度
        extendSubstrings(s, i, i + 1); // 偶数长度
    }
    return cnt;
C
CyC2018 已提交
5950
}
C
CyC2018 已提交
5951

C
CyC2018 已提交
5952 5953 5954 5955 5956 5957
private void extendSubstrings(String s, int start, int end) {
    while (start >= 0 && end < s.length() && s.charAt(start) == s.charAt(end)) {
        start--;
        end++;
        cnt++;
    }
C
CyC2018 已提交
5958 5959
}
```
C
CyC2018 已提交
5960

C
CyC2018 已提交
5961
**判断一个整数是否是回文数** 
C
CyC2018 已提交
5962

C
CyC2018 已提交
5963
[9. Palindrome Number (Easy)](https://leetcode.com/problems/palindrome-number/description/)
C
CyC2018 已提交
5964

C
CyC2018 已提交
5965
要求不能使用额外空间,也就不能将整数转换为字符串进行判断。
C
CyC2018 已提交
5966

C
CyC2018 已提交
5967
将整数分成左右两部分,右边那部分需要转置,然后判断这两部分是否相等。
C
CyC2018 已提交
5968 5969

```java
C
CyC2018 已提交
5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982
public boolean isPalindrome(int x) {
    if (x == 0) {
        return true;
    }
    if (x < 0 || x % 10 == 0) {
        return false;
    }
    int right = 0;
    while (x > right) {
        right = right * 10 + x % 10;
        x /= 10;
    }
    return x == right || x == right / 10;
C
CyC2018 已提交
5983 5984 5985
}
```

C
CyC2018 已提交
5986
**统计二进制字符串中连续 1 和连续 0 数量相同的子字符串个数** 
C
CyC2018 已提交
5987

C
CyC2018 已提交
5988
[696. Count Binary Substrings (Easy)](https://leetcode.com/problems/count-binary-substrings/description/)
C
CyC2018 已提交
5989

C
CyC2018 已提交
5990
```html
C
CyC2018 已提交
5991 5992 5993
Input: "00110011"
Output: 6
Explanation: There are 6 substrings that have equal number of consecutive 1's and 0's: "0011", "01", "1100", "10", "0011", and "01".
C
CyC2018 已提交
5994
```
C
CyC2018 已提交
5995 5996

```java
C
CyC2018 已提交
5997 5998 5999 6000 6001 6002 6003 6004 6005
public int countBinarySubstrings(String s) {
    int preLen = 0, curLen = 1, count = 0;
    for (int i = 1; i < s.length(); i++) {
        if (s.charAt(i) == s.charAt(i - 1)) {
            curLen++;
        } else {
            preLen = curLen;
            curLen = 1;
        }
C
CyC2018 已提交
6006

C
CyC2018 已提交
6007 6008 6009 6010 6011
        if (preLen >= curLen) {
            count++;
        }
    }
    return count;
C
CyC2018 已提交
6012 6013 6014
}
```

C
CyC2018 已提交
6015
## 数组与矩阵
C
CyC2018 已提交
6016

C
CyC2018 已提交
6017
**把数组中的 0 移到末尾** 
C
CyC2018 已提交
6018

C
CyC2018 已提交
6019
[283. Move Zeroes (Easy)](https://leetcode.com/problems/move-zeroes/description/)
C
CyC2018 已提交
6020 6021

```html
C
CyC2018 已提交
6022
For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].
C
CyC2018 已提交
6023 6024 6025
```

```java
C
CyC2018 已提交
6026 6027 6028 6029 6030 6031 6032 6033 6034 6035
public void moveZeroes(int[] nums) {
    int idx = 0;
    for (int num : nums) {
        if (num != 0) {
            nums[idx++] = num;
        }
    }
    while (idx < nums.length) {
        nums[idx++] = 0;
    }
C
CyC2018 已提交
6036 6037 6038
}
```

C
CyC2018 已提交
6039
**改变矩阵维度** 
C
CyC2018 已提交
6040

C
CyC2018 已提交
6041
[566. Reshape the Matrix (Easy)](https://leetcode.com/problems/reshape-the-matrix/description/)
C
CyC2018 已提交
6042 6043

```html
C
CyC2018 已提交
6044
Input:
C
CyC2018 已提交
6045
nums =
C
CyC2018 已提交
6046
[[1,2],
C
CyC2018 已提交
6047 6048
 [3,4]]
r = 1, c = 4
C
CyC2018 已提交
6049

C
CyC2018 已提交
6050 6051
Output:
[[1,2,3,4]]
C
CyC2018 已提交
6052

C
CyC2018 已提交
6053
Explanation:
C
CyC2018 已提交
6054
The row-traversing of nums is [1,2,3,4]. The new reshaped matrix is a 1 * 4 matrix, fill it row by row by using the previous list.
C
CyC2018 已提交
6055 6056 6057
```

```java
C
CyC2018 已提交
6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071
public int[][] matrixReshape(int[][] nums, int r, int c) {
    int m = nums.length, n = nums[0].length;
    if (m * n != r * c) {
        return nums;
    }
    int[][] reshapedNums = new int[r][c];
    int index = 0;
    for (int i = 0; i < r; i++) {
        for (int j = 0; j < c; j++) {
            reshapedNums[i][j] = nums[index / n][index % n];
            index++;
        }
    }
    return reshapedNums;
C
CyC2018 已提交
6072
}
C
CyC2018 已提交
6073
```
C
CyC2018 已提交
6074

C
CyC2018 已提交
6075
**找出数组中最长的连续 1** 
C
CyC2018 已提交
6076

C
CyC2018 已提交
6077
[485. Max Consecutive Ones (Easy)](https://leetcode.com/problems/max-consecutive-ones/description/)
C
CyC2018 已提交
6078 6079

```java
C
CyC2018 已提交
6080 6081 6082 6083 6084 6085 6086
public int findMaxConsecutiveOnes(int[] nums) {
    int max = 0, cur = 0;
    for (int x : nums) {
        cur = x == 0 ? 0 : cur + 1;
        max = Math.max(max, cur);
    }
    return max;
C
CyC2018 已提交
6087 6088 6089
}
```

C
CyC2018 已提交
6090
**有序矩阵查找** 
C
CyC2018 已提交
6091

C
CyC2018 已提交
6092
[240. Search a 2D Matrix II (Medium)](https://leetcode.com/problems/search-a-2d-matrix-ii/description/)
C
CyC2018 已提交
6093 6094

```html
C
CyC2018 已提交
6095
[
C
CyC2018 已提交
6096 6097 6098
   [ 1,  5,  9],
   [10, 11, 13],
   [12, 13, 15]
C
CyC2018 已提交
6099
]
C
CyC2018 已提交
6100 6101 6102
```

```java
C
CyC2018 已提交
6103 6104 6105 6106 6107 6108 6109 6110 6111 6112
public boolean searchMatrix(int[][] matrix, int target) {
    if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return false;
    int m = matrix.length, n = matrix[0].length;
    int row = 0, col = n - 1;
    while (row < m && col >= 0) {
        if (target == matrix[row][col]) return true;
        else if (target < matrix[row][col]) col--;
        else row++;
    }
    return false;
C
CyC2018 已提交
6113 6114 6115
}
```

C
CyC2018 已提交
6116
**有序矩阵的 Kth Element** 
C
CyC2018 已提交
6117

C
CyC2018 已提交
6118
[378. Kth Smallest Element in a Sorted Matrix ((Medium))](https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/description/)
C
CyC2018 已提交
6119

C
CyC2018 已提交
6120
```html
C
CyC2018 已提交
6121 6122 6123 6124
matrix = [
  [ 1,  5,  9],
  [10, 11, 13],
  [12, 13, 15]
C
CyC2018 已提交
6125
],
C
CyC2018 已提交
6126
k = 8,
C
CyC2018 已提交
6127

C
CyC2018 已提交
6128
return 13.
C
CyC2018 已提交
6129 6130
```

C
CyC2018 已提交
6131
解题参考:[Share my thoughts and Clean Java Code](https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/discuss/85173)
C
CyC2018 已提交
6132

C
CyC2018 已提交
6133
二分查找解法:
C
CyC2018 已提交
6134

C
CyC2018 已提交
6135
```java
C
CyC2018 已提交
6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150
public int kthSmallest(int[][] matrix, int k) {
    int m = matrix.length, n = matrix[0].length;
    int lo = matrix[0][0], hi = matrix[m - 1][n - 1];
    while (lo <= hi) {
        int mid = lo + (hi - lo) / 2;
        int cnt = 0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n && matrix[i][j] <= mid; j++) {
                cnt++;
            }
        }
        if (cnt < k) lo = mid + 1;
        else hi = mid - 1;
    }
    return lo;
C
CyC2018 已提交
6151 6152 6153
}
```

C
CyC2018 已提交
6154
堆解法:
C
CyC2018 已提交
6155 6156

```java
C
CyC2018 已提交
6157 6158 6159 6160 6161 6162 6163 6164 6165 6166
public int kthSmallest(int[][] matrix, int k) {
    int m = matrix.length, n = matrix[0].length;
    PriorityQueue<Tuple> pq = new PriorityQueue<Tuple>();
    for(int j = 0; j < n; j++) pq.offer(new Tuple(0, j, matrix[0][j]));
    for(int i = 0; i < k - 1; i++) { // 小根堆,去掉 k - 1 个堆顶元素,此时堆顶元素就是第 k 的数
        Tuple t = pq.poll();
        if(t.x == m - 1) continue;
        pq.offer(new Tuple(t.x + 1, t.y, matrix[t.x + 1][t.y]));
    }
    return pq.poll().val;
C
CyC2018 已提交
6167 6168
}

C
CyC2018 已提交
6169 6170 6171 6172 6173
class Tuple implements Comparable<Tuple> {
    int x, y, val;
    public Tuple(int x, int y, int val) {
        this.x = x; this.y = y; this.val = val;
    }
C
CyC2018 已提交
6174

C
CyC2018 已提交
6175 6176 6177 6178
    @Override
    public int compareTo(Tuple that) {
        return this.val - that.val;
    }
C
CyC2018 已提交
6179 6180 6181
}
```

C
CyC2018 已提交
6182
**一个数组元素在 [1, n] 之间,其中一个数被替换为另一个数,找出重复的数和丢失的数** 
C
CyC2018 已提交
6183

C
CyC2018 已提交
6184
[645. Set Mismatch (Easy)](https://leetcode.com/problems/set-mismatch/description/)
C
CyC2018 已提交
6185 6186

```html
C
CyC2018 已提交
6187 6188
Input: nums = [1,2,2,4]
Output: [2,3]
C
CyC2018 已提交
6189
```
C
CyC2018 已提交
6190

C
CyC2018 已提交
6191
```html
C
CyC2018 已提交
6192 6193
Input: nums = [1,2,2,4]
Output: [2,3]
C
CyC2018 已提交
6194 6195
```

C
CyC2018 已提交
6196
最直接的方法是先对数组进行排序,这种方法时间复杂度为 O(NlogN)。本题可以以 O(N) 的时间复杂度、O(1) 空间复杂度来求解。
C
CyC2018 已提交
6197

C
CyC2018 已提交
6198
主要思想是通过交换数组元素,使得数组上的元素在正确的位置上。
C
CyC2018 已提交
6199 6200

```java
C
CyC2018 已提交
6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212
public int[] findErrorNums(int[] nums) {
    for (int i = 0; i < nums.length; i++) {
        while (nums[i] != i + 1 && nums[nums[i] - 1] != nums[i]) {
            swap(nums, i, nums[i] - 1);
        }
    }
    for (int i = 0; i < nums.length; i++) {
        if (nums[i] != i + 1) {
            return new int[]{nums[i], i + 1};
        }
    }
    return null;
C
CyC2018 已提交
6213 6214
}

C
CyC2018 已提交
6215 6216 6217 6218
private void swap(int[] nums, int i, int j) {
    int tmp = nums[i];
    nums[i] = nums[j];
    nums[j] = tmp;
C
CyC2018 已提交
6219 6220 6221
}
```

C
CyC2018 已提交
6222
类似题目:
C
CyC2018 已提交
6223

C
CyC2018 已提交
6224 6225
- [448. Find All Numbers Disappeared in an Array (Easy)](https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/description/),寻找所有丢失的元素
- [442. Find All Duplicates in an Array (Medium)](https://leetcode.com/problems/find-all-duplicates-in-an-array/description/),寻找所有重复的元素。
C
CyC2018 已提交
6226

C
CyC2018 已提交
6227
**找出数组中重复的数,数组值在 [1, n] 之间** 
C
CyC2018 已提交
6228

C
CyC2018 已提交
6229
[287. Find the Duplicate Number (Medium)](https://leetcode.com/problems/find-the-duplicate-number/description/)
C
CyC2018 已提交
6230

C
CyC2018 已提交
6231
要求不能修改数组,也不能使用额外的空间。
C
CyC2018 已提交
6232

C
CyC2018 已提交
6233
二分查找解法:
C
CyC2018 已提交
6234 6235

```java
C
CyC2018 已提交
6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247
public int findDuplicate(int[] nums) {
     int l = 1, h = nums.length - 1;
     while (l <= h) {
         int mid = l + (h - l) / 2;
         int cnt = 0;
         for (int i = 0; i < nums.length; i++) {
             if (nums[i] <= mid) cnt++;
         }
         if (cnt > mid) h = mid - 1;
         else l = mid + 1;
     }
     return l;
C
CyC2018 已提交
6248
}
C
CyC2018 已提交
6249
```
C
CyC2018 已提交
6250

C
CyC2018 已提交
6251 6252 6253
双指针解法,类似于有环链表中找出环的入口:

```java
C
CyC2018 已提交
6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265
public int findDuplicate(int[] nums) {
    int slow = nums[0], fast = nums[nums[0]];
    while (slow != fast) {
        slow = nums[slow];
        fast = nums[nums[fast]];
    }
    fast = 0;
    while (slow != fast) {
        slow = nums[slow];
        fast = nums[fast];
    }
    return slow;
C
CyC2018 已提交
6266 6267 6268
}
```

C
CyC2018 已提交
6269
**数组相邻差值的个数** 
C
CyC2018 已提交
6270

C
CyC2018 已提交
6271
[667. Beautiful Arrangement II (Medium)](https://leetcode.com/problems/beautiful-arrangement-ii/description/)
C
CyC2018 已提交
6272 6273

```html
C
CyC2018 已提交
6274 6275 6276
Input: n = 3, k = 2
Output: [1, 3, 2]
Explanation: The [1, 3, 2] has three different positive integers ranging from 1 to 3, and the [2, 1] has exactly 2 distinct integers: 1 and 2.
C
CyC2018 已提交
6277 6278
```

C
CyC2018 已提交
6279
题目描述:数组元素为 1\~n 的整数,要求构建数组,使得相邻元素的差值不相同的个数为 k。
C
CyC2018 已提交
6280

C
CyC2018 已提交
6281
让前 k+1 个元素构建出 k 个不相同的差值,序列为:1 k+1 2 k 3 k-1 ... k/2 k/2+1.
C
CyC2018 已提交
6282

C
CyC2018 已提交
6283
```java
C
CyC2018 已提交
6284 6285 6286 6287 6288 6289 6290 6291 6292 6293
public int[] constructArray(int n, int k) {
    int[] ret = new int[n];
    ret[0] = 1;
    for (int i = 1, interval = k; i <= k; i++, interval--) {
        ret[i] = i % 2 == 1 ? ret[i - 1] + interval : ret[i - 1] - interval;
    }
    for (int i = k + 1; i < n; i++) {
        ret[i] = i + 1;
    }
    return ret;
C
CyC2018 已提交
6294 6295
}
```
C
CyC2018 已提交
6296

C
CyC2018 已提交
6297
**数组的度** 
C
CyC2018 已提交
6298

C
CyC2018 已提交
6299
[697. Degree of an Array (Easy)](https://leetcode.com/problems/degree-of-an-array/description/)
C
CyC2018 已提交
6300

C
CyC2018 已提交
6301
```html
C
CyC2018 已提交
6302 6303
Input: [1,2,2,3,1,4,2]
Output: 6
C
CyC2018 已提交
6304
```
C
CyC2018 已提交
6305

C
CyC2018 已提交
6306
题目描述:数组的度定义为元素出现的最高频率,例如上面的数组度为 3。要求找到一个最小的子数组,这个子数组的度和原数组一样。
C
CyC2018 已提交
6307 6308

```java
C
CyC2018 已提交
6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332
public int findShortestSubArray(int[] nums) {
    Map<Integer, Integer> numsCnt = new HashMap<>();
    Map<Integer, Integer> numsLastIndex = new HashMap<>();
    Map<Integer, Integer> numsFirstIndex = new HashMap<>();
    for (int i = 0; i < nums.length; i++) {
        int num = nums[i];
        numsCnt.put(num, numsCnt.getOrDefault(num, 0) + 1);
        numsLastIndex.put(num, i);
        if (!numsFirstIndex.containsKey(num)) {
            numsFirstIndex.put(num, i);
        }
    }
    int maxCnt = 0;
    for (int num : nums) {
        maxCnt = Math.max(maxCnt, numsCnt.get(num));
    }
    int ret = nums.length;
    for (int i = 0; i < nums.length; i++) {
        int num = nums[i];
        int cnt = numsCnt.get(num);
        if (cnt != maxCnt) continue;
        ret = Math.min(ret, numsLastIndex.get(num) - numsFirstIndex.get(num) + 1);
    }
    return ret;
C
CyC2018 已提交
6333 6334
}
```
C
CyC2018 已提交
6335

C
CyC2018 已提交
6336
**对角元素相等的矩阵** 
C
CyC2018 已提交
6337

C
CyC2018 已提交
6338
[766. Toeplitz Matrix (Easy)](https://leetcode.com/problems/toeplitz-matrix/description/)
C
CyC2018 已提交
6339

C
CyC2018 已提交
6340 6341 6342 6343
```html
1234
5123
9512
C
CyC2018 已提交
6344

C
CyC2018 已提交
6345
In the above grid, the diagonals are "[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]", and in each diagonal all elements are the same, so the answer is True.
C
CyC2018 已提交
6346
```
C
CyC2018 已提交
6347

C
CyC2018 已提交
6348
```java
C
CyC2018 已提交
6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360
public boolean isToeplitzMatrix(int[][] matrix) {
    for (int i = 0; i < matrix[0].length; i++) {
        if (!check(matrix, matrix[0][i], 0, i)) {
            return false;
        }
    }
    for (int i = 0; i < matrix.length; i++) {
        if (!check(matrix, matrix[i][0], i, 0)) {
            return false;
        }
    }
    return true;
C
CyC2018 已提交
6361
}
C
CyC2018 已提交
6362

C
CyC2018 已提交
6363 6364 6365 6366 6367 6368 6369 6370
private boolean check(int[][] matrix, int expectValue, int row, int col) {
    if (row >= matrix.length || col >= matrix[0].length) {
        return true;
    }
    if (matrix[row][col] != expectValue) {
        return false;
    }
    return check(matrix, expectValue, row + 1, col + 1);
C
CyC2018 已提交
6371 6372 6373
}
```

C
CyC2018 已提交
6374
**嵌套数组** 
C
CyC2018 已提交
6375

C
CyC2018 已提交
6376
[565. Array Nesting (Medium)](https://leetcode.com/problems/array-nesting/description/)
C
CyC2018 已提交
6377 6378

```html
C
CyC2018 已提交
6379 6380
Input: A = [5,4,0,3,1,6,2]
Output: 4
C
CyC2018 已提交
6381
Explanation:
C
CyC2018 已提交
6382
A[0] = 5, A[1] = 4, A[2] = 0, A[3] = 3, A[4] = 1, A[5] = 6, A[6] = 2.
C
CyC2018 已提交
6383

C
CyC2018 已提交
6384 6385
One of the longest S[K]:
S[0] = {A[0], A[5], A[6], A[2]} = {5, 6, 2, 0}
C
CyC2018 已提交
6386
```
C
CyC2018 已提交
6387

C
CyC2018 已提交
6388
题目描述:S[i] 表示一个集合,集合的第一个元素是 A[i],第二个元素是 A[A[i]],如此嵌套下去。求最大的 S[i]。
C
CyC2018 已提交
6389

C
CyC2018 已提交
6390
```java
C
CyC2018 已提交
6391 6392 6393 6394 6395 6396 6397 6398 6399
public int arrayNesting(int[] nums) {
    int max = 0;
    for (int i = 0; i < nums.length; i++) {
        int cnt = 0;
        for (int j = i; nums[j] != -1; ) {
            cnt++;
            int t = nums[j];
            nums[j] = -1; // 标记该位置已经被访问
            j = t;
C
CyC2018 已提交
6400

C
CyC2018 已提交
6401 6402 6403 6404
        }
        max = Math.max(max, cnt);
    }
    return max;
C
CyC2018 已提交
6405 6406
}
```
C
CyC2018 已提交
6407

C
CyC2018 已提交
6408
**分隔数组** 
C
CyC2018 已提交
6409

C
CyC2018 已提交
6410
[769. Max Chunks To Make Sorted (Medium)](https://leetcode.com/problems/max-chunks-to-make-sorted/description/)
C
CyC2018 已提交
6411

C
CyC2018 已提交
6412
```html
C
CyC2018 已提交
6413 6414
Input: arr = [1,0,2,3,4]
Output: 4
C
CyC2018 已提交
6415
Explanation:
C
CyC2018 已提交
6416 6417
We can split into two chunks, such as [1, 0], [2, 3, 4].
However, splitting into [1, 0], [2], [3], [4] is the highest number of chunks possible.
C
CyC2018 已提交
6418
```
C
CyC2018 已提交
6419

C
CyC2018 已提交
6420
题目描述:分隔数组,使得对每部分排序后数组就为有序。
C
CyC2018 已提交
6421

C
CyC2018 已提交
6422
```java
C
CyC2018 已提交
6423 6424 6425 6426 6427 6428 6429 6430 6431
public int maxChunksToSorted(int[] arr) {
    if (arr == null) return 0;
    int ret = 0;
    int right = arr[0];
    for (int i = 0; i < arr.length; i++) {
        right = Math.max(right, arr[i]);
        if (right == i) ret++;
    }
    return ret;
C
CyC2018 已提交
6432 6433 6434
}
```

C
CyC2018 已提交
6435
## 图
C
CyC2018 已提交
6436

C
CyC2018 已提交
6437
### 二分图
C
CyC2018 已提交
6438 6439 6440

如果可以用两种颜色对图中的节点进行着色,并且保证相邻的节点颜色不同,那么这个图就是二分图。

C
CyC2018 已提交
6441
**判断是否为二分图** 
C
CyC2018 已提交
6442

C
CyC2018 已提交
6443
[785. Is Graph Bipartite? (Medium)](https://leetcode.com/problems/is-graph-bipartite/description/)
C
CyC2018 已提交
6444 6445

```html
C
CyC2018 已提交
6446 6447
Input: [[1,3], [0,2], [1,3], [0,2]]
Output: true
C
CyC2018 已提交
6448
Explanation:
C
CyC2018 已提交
6449
The graph looks like this:
C
CyC2018 已提交
6450
0----1
C
CyC2018 已提交
6451 6452
|    |
|    |
C
CyC2018 已提交
6453
3----2
C
CyC2018 已提交
6454
We can divide the vertices into two groups: {0, 2} and {1, 3}.
C
CyC2018 已提交
6455 6456 6457
```

```html
C
CyC2018 已提交
6458 6459 6460
Example 2:
Input: [[1,2,3], [0,2], [0,1,3], [0,2]]
Output: false
C
CyC2018 已提交
6461
Explanation:
C
CyC2018 已提交
6462
The graph looks like this:
C
CyC2018 已提交
6463
0----1
C
CyC2018 已提交
6464 6465
| \  |
|  \ |
C
CyC2018 已提交
6466
3----2
C
CyC2018 已提交
6467
We cannot find a way to divide the set of nodes into two independent subsets.
C
CyC2018 已提交
6468 6469 6470
```

```java
C
CyC2018 已提交
6471 6472 6473 6474 6475 6476 6477 6478 6479
public boolean isBipartite(int[][] graph) {
    int[] colors = new int[graph.length];
    Arrays.fill(colors, -1);
    for (int i = 0; i < graph.length; i++) {  // 处理图不是连通的情况
        if (colors[i] == -1 && !isBipartite(i, 0, colors, graph)) {
            return false;
        }
    }
    return true;
C
CyC2018 已提交
6480 6481
}

C
CyC2018 已提交
6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492
private boolean isBipartite(int curNode, int curColor, int[] colors, int[][] graph) {
    if (colors[curNode] != -1) {
        return colors[curNode] == curColor;
    }
    colors[curNode] = curColor;
    for (int nextNode : graph[curNode]) {
        if (!isBipartite(nextNode, 1 - curColor, colors, graph)) {
            return false;
        }
    }
    return true;
C
CyC2018 已提交
6493 6494 6495
}
```

C
CyC2018 已提交
6496
### 拓扑排序
C
CyC2018 已提交
6497 6498 6499

常用于在具有先序关系的任务规划中。

C
CyC2018 已提交
6500
**课程安排的合法性** 
C
CyC2018 已提交
6501

C
CyC2018 已提交
6502
[207. Course Schedule (Medium)](https://leetcode.com/problems/course-schedule/description/)
C
CyC2018 已提交
6503 6504

```html
C
CyC2018 已提交
6505 6506
2, [[1,0]]
return true
C
CyC2018 已提交
6507 6508 6509
```

```html
C
CyC2018 已提交
6510 6511
2, [[1,0],[0,1]]
return false
C
CyC2018 已提交
6512 6513 6514 6515 6516 6517 6518
```

题目描述:一个课程可能会先修课程,判断给定的先修课程规定是否合法。

本题不需要使用拓扑排序,只需要检测有向图是否存在环即可。

```java
C
CyC2018 已提交
6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617
public boolean canFinish(int numCourses, int[][] prerequisites) {
    List<Integer>[] graphic = new List[numCourses];
    for (int i = 0; i < numCourses; i++) {
        graphic[i] = new ArrayList<>();
    }
    for (int[] pre : prerequisites) {
        graphic[pre[0]].add(pre[1]);
    }
    boolean[] globalMarked = new boolean[numCourses];
    boolean[] localMarked = new boolean[numCourses];
    for (int i = 0; i < numCourses; i++) {
        if (hasCycle(globalMarked, localMarked, graphic, i)) {
            return false;
        }
    }
    return true;
}

private boolean hasCycle(boolean[] globalMarked, boolean[] localMarked,
                         List<Integer>[] graphic, int curNode) {

    if (localMarked[curNode]) {
        return true;
    }
    if (globalMarked[curNode]) {
        return false;
    }
    globalMarked[curNode] = true;
    localMarked[curNode] = true;
    for (int nextNode : graphic[curNode]) {
        if (hasCycle(globalMarked, localMarked, graphic, nextNode)) {
            return true;
        }
    }
    localMarked[curNode] = false;
    return false;
}
```

**课程安排的顺序** 

[210. Course Schedule II (Medium)](https://leetcode.com/problems/course-schedule-ii/description/)

```html
4, [[1,0],[2,0],[3,1],[3,2]]
There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is [0,1,2,3]. Another correct ordering is[0,2,1,3].
```

使用 DFS 来实现拓扑排序,使用一个栈存储后序遍历结果,这个栈的逆序结果就是拓扑排序结果。

证明:对于任何先序关系:v->w,后序遍历结果可以保证 w 先进入栈中,因此栈的逆序结果中 v 会在 w 之前。

```java
public int[] findOrder(int numCourses, int[][] prerequisites) {
    List<Integer>[] graphic = new List[numCourses];
    for (int i = 0; i < numCourses; i++) {
        graphic[i] = new ArrayList<>();
    }
    for (int[] pre : prerequisites) {
        graphic[pre[0]].add(pre[1]);
    }
    Stack<Integer> postOrder = new Stack<>();
    boolean[] globalMarked = new boolean[numCourses];
    boolean[] localMarked = new boolean[numCourses];
    for (int i = 0; i < numCourses; i++) {
        if (hasCycle(globalMarked, localMarked, graphic, i, postOrder)) {
            return new int[0];
        }
    }
    int[] orders = new int[numCourses];
    for (int i = numCourses - 1; i >= 0; i--) {
        orders[i] = postOrder.pop();
    }
    return orders;
}

private boolean hasCycle(boolean[] globalMarked, boolean[] localMarked, List<Integer>[] graphic,
                         int curNode, Stack<Integer> postOrder) {

    if (localMarked[curNode]) {
        return true;
    }
    if (globalMarked[curNode]) {
        return false;
    }
    globalMarked[curNode] = true;
    localMarked[curNode] = true;
    for (int nextNode : graphic[curNode]) {
        if (hasCycle(globalMarked, localMarked, graphic, nextNode, postOrder)) {
            return true;
        }
    }
    localMarked[curNode] = false;
    postOrder.push(curNode);
    return false;
}
```

### 并查集
C
CyC2018 已提交
6618 6619 6620

并查集可以动态地连通两个点,并且可以非常快速地判断两个点是否连通。

C
CyC2018 已提交
6621
**冗余连接** 
C
CyC2018 已提交
6622

C
CyC2018 已提交
6623
[684. Redundant Connection (Medium)](https://leetcode.com/problems/redundant-connection/description/)
C
CyC2018 已提交
6624 6625

```html
C
CyC2018 已提交
6626 6627 6628 6629 6630 6631
Input: [[1,2], [1,3], [2,3]]
Output: [2,3]
Explanation: The given undirected graph will be like this:
  1
 / \
2 - 3
C
CyC2018 已提交
6632 6633 6634 6635 6636
```

题目描述:有一系列的边连成的图,找出一条边,移除它之后该图能够成为一棵树。

```java
C
CyC2018 已提交
6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647
public int[] findRedundantConnection(int[][] edges) {
    int N = edges.length;
    UF uf = new UF(N);
    for (int[] e : edges) {
        int u = e[0], v = e[1];
        if (uf.connect(u, v)) {
            return e;
        }
        uf.union(u, v);
    }
    return new int[]{-1, -1};
C
CyC2018 已提交
6648 6649
}

C
CyC2018 已提交
6650
private class UF {
C
CyC2018 已提交
6651

C
CyC2018 已提交
6652
    private int[] id;
C
CyC2018 已提交
6653

C
CyC2018 已提交
6654 6655 6656 6657 6658 6659
    UF(int N) {
        id = new int[N + 1];
        for (int i = 0; i < id.length; i++) {
            id[i] = i;
        }
    }
C
CyC2018 已提交
6660

C
CyC2018 已提交
6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672
    void union(int u, int v) {
        int uID = find(u);
        int vID = find(v);
        if (uID == vID) {
            return;
        }
        for (int i = 0; i < id.length; i++) {
            if (id[i] == uID) {
                id[i] = vID;
            }
        }
    }
C
CyC2018 已提交
6673

C
CyC2018 已提交
6674 6675 6676
    int find(int p) {
        return id[p];
    }
C
CyC2018 已提交
6677

C
CyC2018 已提交
6678 6679 6680
    boolean connect(int u, int v) {
        return find(u) == find(v);
    }
C
CyC2018 已提交
6681 6682 6683
}
```

C
CyC2018 已提交
6684
## 位运算
C
CyC2018 已提交
6685

C
CyC2018 已提交
6686
**1. 基本原理** 
C
CyC2018 已提交
6687

C
CyC2018 已提交
6688
0s 表示一串 0,1s 表示一串 1。
C
CyC2018 已提交
6689 6690

```
C
CyC2018 已提交
6691 6692 6693
x ^ 0s = x      x & 0s = 0      x | 0s = x
x ^ 1s = ~x     x & 1s = x      x | 1s = 1s
x ^ x = 0       x & x = x       x | x = x
C
CyC2018 已提交
6694 6695
```

C
CyC2018 已提交
6696 6697 6698
- 利用 x ^ 1s = \~x 的特点,可以将位级表示翻转;利用 x ^ x = 0 的特点,可以将三个数中重复的两个数去除,只留下另一个数。
- 利用 x & 0s = 0 和 x & 1s = x 的特点,可以实现掩码操作。一个数 num 与 mask:00111100 进行位与操作,只保留 num 中与 mask 的 1 部分相对应的位。
- 利用 x | 0s = x 和 x | 1s = 1s 的特点,可以实现设值操作。一个数 num 与 mask:00111100 进行位或操作,将 num 中与 mask 的 1 部分相对应的位都设置为 1。
C
CyC2018 已提交
6699

C
CyC2018 已提交
6700
位与运算技巧:
C
CyC2018 已提交
6701

C
CyC2018 已提交
6702 6703 6704
- n&(n-1) 去除 n 的位级表示中最低的那一位。例如对于二进制表示 10110 **100** ,减去 1 得到 10110**011**,这两个数相与得到 10110**000**
- n&(-n) 得到 n 的位级表示中最低的那一位。-n 得到 n 的反码加 1,对于二进制表示 10110 **100** ,-n 得到 01001**100**,相与得到 00000**100**
- n-n&(\~n+1) 去除 n 的位级表示中最高的那一位。
C
CyC2018 已提交
6705

C
CyC2018 已提交
6706
移位运算:
C
CyC2018 已提交
6707

C
CyC2018 已提交
6708 6709 6710
- \>\> n 为算术右移,相当于除以 2<sup>n</sup>
- \>\>\> n 为无符号右移,左边会补上 0。
- &lt;&lt; n 为算术左移,相当于乘以 2<sup>n</sup>
C
CyC2018 已提交
6711

C
CyC2018 已提交
6712
**2. mask 计算** 
C
CyC2018 已提交
6713

C
CyC2018 已提交
6714
要获取 111111111,将 0 取反即可,\~0。
C
CyC2018 已提交
6715

C
CyC2018 已提交
6716
要得到只有第 i 位为 1 的 mask,将 1 向左移动 i-1 位即可,1&lt;&lt;(i-1) 。例如 1&lt;&lt;4 得到只有第 5 位为 1 的 mask :00010000。
C
CyC2018 已提交
6717

C
CyC2018 已提交
6718
要得到 1 到 i 位为 1 的 mask,1&lt;&lt;(i+1)-1 即可,例如将 1&lt;&lt;(4+1)-1 = 00010000-1 = 00001111。
C
CyC2018 已提交
6719

C
CyC2018 已提交
6720
要得到 1 到 i 位为 0 的 mask,只需将 1 到 i 位为 1 的 mask 取反,即 \~(1&lt;&lt;(i+1)-1)。
C
CyC2018 已提交
6721

C
CyC2018 已提交
6722
**3. Java 中的位操作** 
C
CyC2018 已提交
6723 6724

```html
C
CyC2018 已提交
6725 6726 6727
static int Integer.bitCount();           // 统计 1 的数量
static int Integer.highestOneBit();      // 获得最高位
static String toBinaryString(int i);     // 转换为二进制表示的字符串
C
CyC2018 已提交
6728 6729
```

C
CyC2018 已提交
6730
**统计两个数的二进制表示有多少位不同** 
C
CyC2018 已提交
6731

C
CyC2018 已提交
6732
[461. Hamming Distance (Easy)](https://leetcode.com/problems/hamming-distance/)
C
CyC2018 已提交
6733

C
CyC2018 已提交
6734
```html
C
CyC2018 已提交
6735
Input: x = 1, y = 4
C
CyC2018 已提交
6736

C
CyC2018 已提交
6737
Output: 2
C
CyC2018 已提交
6738 6739

Explanation:
C
CyC2018 已提交
6740 6741 6742
1   (0 0 0 1)
4   (0 1 0 0)
       ↑   ↑
C
CyC2018 已提交
6743

C
CyC2018 已提交
6744
The above arrows point to positions where the corresponding bits are different.
C
CyC2018 已提交
6745 6746
```

C
CyC2018 已提交
6747
对两个数进行异或操作,位级表示不同的那一位为 1,统计有多少个 1 即可。
C
CyC2018 已提交
6748 6749

```java
C
CyC2018 已提交
6750 6751 6752 6753 6754 6755 6756 6757
public int hammingDistance(int x, int y) {
    int z = x ^ y;
    int cnt = 0;
    while(z != 0) {
        if ((z & 1) == 1) cnt++;
        z = z >> 1;
    }
    return cnt;
C
CyC2018 已提交
6758 6759 6760
}
```

C
CyC2018 已提交
6761
使用 z&(z-1) 去除 z 位级表示最低的那一位。
C
CyC2018 已提交
6762 6763

```java
C
CyC2018 已提交
6764 6765 6766 6767 6768 6769 6770 6771
public int hammingDistance(int x, int y) {
    int z = x ^ y;
    int cnt = 0;
    while (z != 0) {
        z &= (z - 1);
        cnt++;
    }
    return cnt;
C
CyC2018 已提交
6772 6773 6774
}
```

C
CyC2018 已提交
6775
可以使用 Integer.bitcount() 来统计 1 个的个数。
C
CyC2018 已提交
6776 6777

```java
C
CyC2018 已提交
6778 6779
public int hammingDistance(int x, int y) {
    return Integer.bitCount(x ^ y);
C
CyC2018 已提交
6780 6781 6782
}
```

C
CyC2018 已提交
6783
**数组中唯一一个不重复的元素** 
C
CyC2018 已提交
6784

C
CyC2018 已提交
6785
[136. Single Number (Easy)](https://leetcode.com/problems/single-number/description/)
C
CyC2018 已提交
6786 6787

```html
C
CyC2018 已提交
6788 6789
Input: [4,1,2,1,2]
Output: 4
C
CyC2018 已提交
6790 6791
```

C
CyC2018 已提交
6792
两个相同的数异或的结果为 0,对所有数进行异或操作,最后的结果就是单独出现的那个数。
C
CyC2018 已提交
6793 6794

```java
C
CyC2018 已提交
6795 6796 6797 6798
public int singleNumber(int[] nums) {
    int ret = 0;
    for (int n : nums) ret = ret ^ n;
    return ret;
C
CyC2018 已提交
6799 6800 6801
}
```

C
CyC2018 已提交
6802
**找出数组中缺失的那个数** 
C
CyC2018 已提交
6803

C
CyC2018 已提交
6804
[268. Missing Number (Easy)](https://leetcode.com/problems/missing-number/description/)
C
CyC2018 已提交
6805 6806

```html
C
CyC2018 已提交
6807 6808
Input: [3,0,1]
Output: 2
C
CyC2018 已提交
6809 6810
```

C
CyC2018 已提交
6811
题目描述:数组元素在 0-n 之间,但是有一个数是缺失的,要求找到这个缺失的数。
C
CyC2018 已提交
6812 6813

```java
C
CyC2018 已提交
6814 6815 6816 6817 6818 6819
public int missingNumber(int[] nums) {
    int ret = 0;
    for (int i = 0; i < nums.length; i++) {
        ret = ret ^ i ^ nums[i];
    }
    return ret ^ nums.length;
C
CyC2018 已提交
6820 6821 6822
}
```

C
CyC2018 已提交
6823
**数组中不重复的两个元素** 
C
CyC2018 已提交
6824

C
CyC2018 已提交
6825
[260. Single Number III (Medium)](https://leetcode.com/problems/single-number-iii/description/)
C
CyC2018 已提交
6826 6827 6828 6829 6830

两个不相等的元素在位级表示上必定会有一位存在不同。

将数组的所有元素异或得到的结果为不存在重复的两个元素异或的结果。

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

```java
C
CyC2018 已提交
6834 6835 6836 6837 6838 6839 6840 6841 6842 6843
public int[] singleNumber(int[] nums) {
    int diff = 0;
    for (int num : nums) diff ^= num;
    diff &= -diff;  // 得到最右一位
    int[] ret = new int[2];
    for (int num : nums) {
        if ((num & diff) == 0) ret[0] ^= num;
        else ret[1] ^= num;
    }
    return ret;
C
CyC2018 已提交
6844 6845 6846
}
```

C
CyC2018 已提交
6847
**翻转一个数的比特位** 
C
CyC2018 已提交
6848

C
CyC2018 已提交
6849
[190. Reverse Bits (Easy)](https://leetcode.com/problems/reverse-bits/description/)
C
CyC2018 已提交
6850 6851

```java
C
CyC2018 已提交
6852 6853 6854 6855 6856 6857 6858 6859
public int reverseBits(int n) {
    int ret = 0;
    for (int i = 0; i < 32; i++) {
        ret <<= 1;
        ret |= (n & 1);
        n >>>= 1;
    }
    return ret;
C
CyC2018 已提交
6860 6861 6862
}
```

C
CyC2018 已提交
6863
如果该函数需要被调用很多次,可以将 int 拆成 4 个 byte,然后缓存 byte 对应的比特位翻转,最后再拼接起来。
C
CyC2018 已提交
6864 6865

```java
C
CyC2018 已提交
6866
private static Map<Byte, Integer> cache = new HashMap<>();
C
CyC2018 已提交
6867

C
CyC2018 已提交
6868 6869 6870 6871 6872 6873 6874 6875
public int reverseBits(int n) {
    int ret = 0;
    for (int i = 0; i < 4; i++) {
        ret <<= 8;
        ret |= reverseByte((byte) (n & 0b11111111));
        n >>= 8;
    }
    return ret;
C
CyC2018 已提交
6876 6877
}

C
CyC2018 已提交
6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888
private int reverseByte(byte b) {
    if (cache.containsKey(b)) return cache.get(b);
    int ret = 0;
    byte t = b;
    for (int i = 0; i < 8; i++) {
        ret <<= 1;
        ret |= t & 1;
        t >>= 1;
    }
    cache.put(b, ret);
    return ret;
C
CyC2018 已提交
6889 6890 6891
}
```

C
CyC2018 已提交
6892
**不用额外变量交换两个整数** 
C
CyC2018 已提交
6893

C
CyC2018 已提交
6894
[程序员代码面试指南 :P317](#)
C
CyC2018 已提交
6895 6896

```java
C
CyC2018 已提交
6897 6898 6899
a = a ^ b;
b = a ^ b;
a = a ^ b;
C
CyC2018 已提交
6900 6901
```

C
CyC2018 已提交
6902
**判断一个数是不是 2 的 n 次方** 
C
CyC2018 已提交
6903

C
CyC2018 已提交
6904
[231. Power of Two (Easy)](https://leetcode.com/problems/power-of-two/description/)
C
CyC2018 已提交
6905

C
CyC2018 已提交
6906
二进制表示只有一个 1 存在。
C
CyC2018 已提交
6907 6908

```java
C
CyC2018 已提交
6909 6910
public boolean isPowerOfTwo(int n) {
    return n > 0 && Integer.bitCount(n) == 1;
C
CyC2018 已提交
6911 6912 6913
}
```

C
CyC2018 已提交
6914
利用 1000 & 0111 == 0 这种性质,得到以下解法:
C
CyC2018 已提交
6915 6916

```java
C
CyC2018 已提交
6917 6918
public boolean isPowerOfTwo(int n) {
    return n > 0 && (n & (n - 1)) == 0;
C
CyC2018 已提交
6919 6920 6921
}
```

C
CyC2018 已提交
6922
**判断一个数是不是 4 的 n 次方** 
C
CyC2018 已提交
6923

C
CyC2018 已提交
6924
[342. Power of Four (Easy)](https://leetcode.com/problems/power-of-four/)
C
CyC2018 已提交
6925

C
CyC2018 已提交
6926
这种数在二进制表示中有且只有一个奇数位为 1,例如 16(10000)。
C
CyC2018 已提交
6927 6928

```java
C
CyC2018 已提交
6929 6930
public boolean isPowerOfFour(int num) {
    return num > 0 && (num & (num - 1)) == 0 && (num & 0b01010101010101010101010101010101) != 0;
C
CyC2018 已提交
6931 6932 6933
}
```

C
CyC2018 已提交
6934
也可以使用正则表达式进行匹配。
C
CyC2018 已提交
6935 6936

```java
C
CyC2018 已提交
6937 6938
public boolean isPowerOfFour(int num) {
    return Integer.toString(num, 4).matches("10*");
C
CyC2018 已提交
6939 6940 6941
}
```

C
CyC2018 已提交
6942
**判断一个数的位级表示是否不会出现连续的 0 和 1** 
C
CyC2018 已提交
6943

C
CyC2018 已提交
6944
[693. Binary Number with Alternating Bits (Easy)](https://leetcode.com/problems/binary-number-with-alternating-bits/description/)
C
CyC2018 已提交
6945

C
CyC2018 已提交
6946
```html
C
CyC2018 已提交
6947 6948
Input: 10
Output: True
C
CyC2018 已提交
6949
Explanation:
C
CyC2018 已提交
6950
The binary representation of 10 is: 1010.
C
CyC2018 已提交
6951

C
CyC2018 已提交
6952 6953
Input: 11
Output: False
C
CyC2018 已提交
6954
Explanation:
C
CyC2018 已提交
6955
The binary representation of 11 is: 1011.
C
CyC2018 已提交
6956 6957
```

C
CyC2018 已提交
6958
对于 1010 这种位级表示的数,把它向右移动 1 位得到 101,这两个数每个位都不同,因此异或得到的结果为 1111。
C
CyC2018 已提交
6959 6960

```java
C
CyC2018 已提交
6961 6962 6963
public boolean hasAlternatingBits(int n) {
    int a = (n ^ (n >> 1));
    return (a & (a + 1)) == 0;
C
CyC2018 已提交
6964 6965 6966
}
```

C
CyC2018 已提交
6967
**求一个数的补码** 
C
CyC2018 已提交
6968

C
CyC2018 已提交
6969
[476. Number Complement (Easy)](https://leetcode.com/problems/number-complement/description/)
C
CyC2018 已提交
6970 6971

```html
C
CyC2018 已提交
6972 6973 6974
Input: 5
Output: 2
Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.
C
CyC2018 已提交
6975 6976
```

C
CyC2018 已提交
6977
题目描述:不考虑二进制表示中的首 0 部分。
C
CyC2018 已提交
6978

C
CyC2018 已提交
6979
对于 00000101,要求补码可以将它与 00000111 进行异或操作。那么问题就转换为求掩码 00000111。
C
CyC2018 已提交
6980 6981

```java
C
CyC2018 已提交
6982 6983 6984 6985 6986 6987
public int findComplement(int num) {
    if (num == 0) return 1;
    int mask = 1 << 30;
    while ((num & mask) == 0) mask >>= 1;
    mask = (mask << 1) - 1;
    return num ^ mask;
C
CyC2018 已提交
6988 6989 6990
}
```

C
CyC2018 已提交
6991
可以利用 Java 的 Integer.highestOneBit() 方法来获得含有首 1 的数。
C
CyC2018 已提交
6992 6993

```java
C
CyC2018 已提交
6994 6995 6996 6997 6998
public int findComplement(int num) {
    if (num == 0) return 1;
    int mask = Integer.highestOneBit(num);
    mask = (mask << 1) - 1;
    return num ^ mask;
C
CyC2018 已提交
6999 7000 7001
}
```

C
CyC2018 已提交
7002
对于 10000000 这样的数要扩展成 11111111,可以利用以下方法:
C
CyC2018 已提交
7003 7004

```html
C
CyC2018 已提交
7005 7006 7007
mask |= mask >> 1    11000000
mask |= mask >> 2    11110000
mask |= mask >> 4    11111111
C
CyC2018 已提交
7008 7009 7010
```

```java
C
CyC2018 已提交
7011 7012 7013 7014 7015 7016 7017 7018
public int findComplement(int num) {
    int mask = num;
    mask |= mask >> 1;
    mask |= mask >> 2;
    mask |= mask >> 4;
    mask |= mask >> 8;
    mask |= mask >> 16;
    return (mask ^ num);
C
CyC2018 已提交
7019 7020 7021
}
```

C
CyC2018 已提交
7022
**实现整数的加法** 
C
CyC2018 已提交
7023

C
CyC2018 已提交
7024
[371. Sum of Two Integers (Easy)](https://leetcode.com/problems/sum-of-two-integers/description/)
C
CyC2018 已提交
7025

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

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

```java
C
CyC2018 已提交
7031 7032
public int getSum(int a, int b) {
    return b == 0 ? a : getSum((a ^ b), (a & b) << 1);
C
CyC2018 已提交
7033 7034 7035
}
```

C
CyC2018 已提交
7036
**字符串数组最大乘积** 
C
CyC2018 已提交
7037

C
CyC2018 已提交
7038
[318. Maximum Product of Word Lengths (Medium)](https://leetcode.com/problems/maximum-product-of-word-lengths/description/)
C
CyC2018 已提交
7039 7040

```html
C
CyC2018 已提交
7041 7042 7043
Given ["abcw", "baz", "foo", "bar", "xtfn", "abcdef"]
Return 16
The two words can be "abcw", "xtfn".
C
CyC2018 已提交
7044 7045 7046 7047
```

题目描述:字符串数组的字符串只含有小写字符。求解字符串数组中两个字符串长度的最大乘积,要求这两个字符串不能含有相同字符。

C
CyC2018 已提交
7048
本题主要问题是判断两个字符串是否含相同字符,由于字符串只含有小写字符,总共 26 位,因此可以用一个 32 位的整数来存储每个字符是否出现过。
C
CyC2018 已提交
7049 7050

```java
C
CyC2018 已提交
7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067
public int maxProduct(String[] words) {
    int n = words.length;
    int[] val = new int[n];
    for (int i = 0; i < n; i++) {
        for (char c : words[i].toCharArray()) {
            val[i] |= 1 << (c - 'a');
        }
    }
    int ret = 0;
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
            if ((val[i] & val[j]) == 0) {
                ret = Math.max(ret, words[i].length() * words[j].length());
            }
        }
    }
    return ret;
C
CyC2018 已提交
7068 7069 7070
}
```

C
CyC2018 已提交
7071
**统计从 0 \~ n 每个数的二进制表示中 1 的个数** 
C
CyC2018 已提交
7072

C
CyC2018 已提交
7073
[338. Counting Bits (Medium)](https://leetcode.com/problems/counting-bits/description/)
C
CyC2018 已提交
7074

C
CyC2018 已提交
7075
对于数字 6(110),它可以看成是 4(100) 再加一个 2(10),因此 dp[i] = dp[i&(i-1)] + 1;
C
CyC2018 已提交
7076 7077

```java
C
CyC2018 已提交
7078 7079 7080 7081 7082 7083
public int[] countBits(int num) {
    int[] ret = new int[num + 1];
    for(int i = 1; i <= num; i++){
        ret[i] = ret[i&(i-1)] + 1;
    }
    return ret;
C
CyC2018 已提交
7084 7085 7086
}
```

C
CyC2018 已提交
7087
# 参考资料
C
CyC2018 已提交
7088

C
CyC2018 已提交
7089 7090 7091 7092 7093 7094
- [Leetcode](https://leetcode.com/problemset/algorithms/?status=Todo)
- Weiss M A, 冯舜玺. 数据结构与算法分析——C 语言描述[J]. 2004.
- Sedgewick R. Algorithms[M]. Pearson Education India, 1988.
- 何海涛, 软件工程师. 剑指 Offer: 名企面试官精讲典型编程题[M]. 电子工业出版社, 2014.
- 《编程之美》小组. 编程之美[M]. 电子工业出版社, 2008.
- 左程云. 程序员代码面试指南[M]. 电子工业出版社, 2015.