LeetCode Java题解

  1. Awesome Java Leetcode
    1. Easy
    2. Medium
    3. Hard
  2. 001 Two Sum
    1. Description
    2. 思路 0
    3. 思路 1
  3. 002 Add Two Numbers
    1. Description
    2. 思路
  4. 003 Longest Substring Without Repeating Characters
    1. Description
    2. 思路
  5. 004 Median of Two Sorted Arrays
    1. Description
    2. 思路
  6. 005 Longest Palindromic Substring
    1. Description
    2. 思路 0
    3. 思路 1
    4. 思路 2
      1. 背景
      2. 分析
  7. 006 ZigZag Conversion
    1. Description
    2. 思路 0
    3. 思路 1
  8. 007 Reverse Integer
    1. Description
    2. 思路
  9. 008 String to Integer (atoi)
    1. Description
    2. 思路
  10. 009 Palindrome Number
    1. Description
    2. 思路 0
    3. 思路 1
  11. 010 Regular Expression Matching
    1. Description
    2. 思路 0
    3. 思路 1
    4. 思路 2
  12. 011 Container With Most Water
    1. Description
    2. 思路
  13. 012 Integer to Roman
    1. Description
    2. 思路
  14. 013 Roman to Integer
    1. Description
    2. 思路
  15. 014 Longest Common Prefix
    1. Description
    2. 思路
  16. 015 3Sum
    1. Description
    2. 思路
  17. 016 3Sum Closest
    1. Description
    2. 思路
  18. 017 Letter Combinations of a Phone Number
    1. Description
    2. 思路 0
    3. 思路 1
  19. 018 4Sum
    1. Description
    2. 思路 0
    3. 思路 1
  20. 019 Remove Nth Node From End of List
    1. Description
    2. 思路
  21. 020 Valid Parentheses
    1. Description
    2. 思路
  22. 021 Merge Two Sorted Lists
    1. Description
    2. 思路
  23. 022 Generate Parentheses
    1. Description
    2. 思路 0
    3. 思路 1
  24. 023 Merge k Sorted Lists
    1. Description
    2. 思路 0
    3. 思路 1
  25. 024 Swap Nodes in Pairs
    1. Description
    2. 思路 0
    3. 思路 1
  26. 025 Reverse Nodes in k-Group
    1. Description
    2. 思路
  27. 026 Remove Duplicates from Sorted Array
    1. Description
    2. 思路
  28. 027 Remove Element
    1. Description
    2. 思路
  29. 028 Implement strStr()
    1. Description
    2. 思路
  30. 029 Divide Two Integers
    1. Description
    2. 思路
  31. 033 Search in Rotated Sorted Array
    1. Description
    2. 思路
  32. 035 Search Insert Position
    1. Description
    2. 思路
  33. 038 Count and Say
    1. Description
    2. 思路
  34. 043 Multiply Strings
    1. Description
    2. 思路
  35. 044 Wildcard Matching
    1. Description
    2. 思路 0
    3. 思路 1
  36. 049 Group Anagrams
    1. Description
    2. 思路
  37. 050 Pow(x, n)
    1. Description
    2. 思路
  38. 053 Maximum Subarray
    1. Description
    2. 思路 0
    3. 思路 1
  39. 056 Merge Intervals
    1. Description
    2. 思路
  40. 057 Insert Interval
    1. Description
    2. 思路
  41. 058 Length of Last Word
    1. Description
    2. 思路
  42. 066 Plus One
    1. Description
    2. 思路
  43. 067 Add Binary
    1. Description
    2. 思路
  44. 068 Text Justification
    1. Description
    2. 思路
  45. 069 Sqrt(x)
    1. Description
    2. 思路
  46. 070 Climbing Stairs
    1. Description
    2. 思路
  47. 083Remove Duplicates from Sorted List
    1. Description
    2. 思路
  48. 088 Merge Sorted Array
    1. Description
    2. 思路
  49. 100 Same Tree
    1. Description
    2. 思路
  50. 101 Symmetric Tree
    1. Description
    2. 思路 0
    3. 思路 1
  51. 104 Maximum Depth of Binary Tree
    1. Description
    2. 思路
  52. 107 Binary Tree Level Order Traversal II
    1. Description
    2. 思路 0
    3. 思路 1
  53. 108 Convert Sorted Array to Binary Search Tree
    1. Description
    2. 思路
  54. 110 Balanced Binary Tree
    1. Description
    2. 思路
  55. 111 Minimum Depth of Binary Tree
    1. Description
    2. 思路 0
    3. 思路 1
  56. 112 Path Sum
    1. Description
    2. 思路
  57. 118 Pascal’s Triangle
    1. Description
    2. 思路
  58. 119 Pascal’s Triangle II
    1. Description
    2. 思路
  59. 121 Best Time to Buy and Sell Stock
    1. Description
    2. 思路
  60. 122 Best Time to Buy and Sell Stock II
    1. Description
    2. 思路
  61. 543 Diameter of Binary Tree
    1. Description
    2. 思路
  62. 554 Brick Wall
    1. Description
    2. 思路

Awesome Java Leetcode

镇楼诗:

明有科举八股,今有 LeetCode。
八股定格式而取文采心意,LeetCode 定题目且重答案背诵。
美其名曰:”practice makes perfect.”
为何今不如古?
非也非也,
科举为国取士,LeetCode 为 Google 筛码工,各取所需也。

Easy

# Title Tag
1 Two Sum Array, Hash Table
7 Reverse Integer Math
9 Palindrome Number Math
13 Roman to Integer Math, String
14 Longest Common Prefix String
20 Valid Parentheses Stack, String
21 Merge Two Sorted Lists Linked List
26 Remove Duplicates from Sorted Array Array, Two Pointers
27 Remove Element Array, Two Pointers
28 Implement strStr() Two Pointers, String
35 Search Insert Position String
38 Count and Say String
53 Maximum Subarray Array, Divide and Conquer, Dynamic Programming
58 Length of Last Word String
66 Plus One Array, Math
67 Add Binary Math, String
69 Sqrt(x) Binary Search, Math
70 Climbing Stairs Dynamic Programming
83 Remove Duplicates from Sorted List Linked List
88 Merge Sorted Array Array, Two Pointers
100 Same Tree Tree, Depth-first Search
101 Symmetric Tree Tree, Depth-first Search, Breadth-first Search
104 Maximum Depth of Binary Tree Tree, Depth-first Search
107 Binary Tree Level Order Traversal II Tree, Breadth-first Search
108 Convert Sorted Array to Binary Search Tree Tree, Depth-first Search
110 Balanced Binary Tree Tree, Depth-first Search
111 Minimum Depth of Binary Tree Tree, Depth-first Search, Breadth-first Search
112 Path Sum Tree, Depth-first Search
118 Pascal’s Triangle Array
119 Pascal’s Triangle II Array
121 Best Time to Buy and Sell Stock Array, Dynamic Programmin
122 Best Time to Buy and Sell Stock II Array, Greedy
543 Diameter of Binary Tree Tree

Medium

# Title Tag
2 Add Two Numbers Linked List, Math
3 Longest Substring Without Repeating Characters Hash Table, Two Pointers, String
5 Longest Palindromic Substring String
6 ZigZag Conversion String
8 String to Integer (atoi) Math, String
11 Container With Most Water Array, Two Pointers
12 Integer to Roman Math, String
15 3Sum Array, Two Pointers
16 3Sum Closest Array, Two Pointers
17 Letter Combinations of a Phone Number String, Backtracking
18 4Sum Array, Hash Table, Two Pointers
19 Remove Nth Node From End of List Linked List, Two Pointers
22 Generate Parentheses String, Backtracking
24 Swap Nodes in Pairs Linked List
29 Divide Two Integers Math, Binary Search
33 Search in Rotated Sorted Array Arrays, Binary Search
43 Multiply Strings Math, String
49 Group Anagrams Hash Table, String
50 Pow(x, n) Math, Binary Search
56 Merge Intervals Array, Sort
554 Brick Wall Hash Table

Hard

# Title Tag
4 Median of Two Sorted Arrays Array, Binary Search, Divide and Conquer
10 Regular Expression Matching String, Dynamic Programming, Backtracking
23 Merge k Sorted Lists Linked List, Divide and Conquer, Heap
25 Reverse Nodes in k-Group Linked List
44 Wildcard Matching String, Dynamic Programming, Backtracking, Greedy
57 Insert Interval Array, Sort
68 Text Justification String

001 Two Sum

Description

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

1
2
3
4
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

Tags: Array, Hash Table

思路 0

题意是让你从给定的数组中找到两个元素的和为指定值的两个索引,最容易的当然是循环两次,复杂度为 O(n^2),首次提交居然是 2ms,打败了 100% 的提交,谜一样的结果,之后再次提交就再也没跑到过 2ms 了。

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public int[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length; ++i) {
for (int j = i + 1; j < nums.length; ++j) {
if (nums[i] + nums[j] == target) {
return new int[]{i, j};
}
}
}
return null;
}
}

思路 1

利用 HashMap 作为存储,键为目标值减去当前元素值,索引为值,比如 i = 0 时,此时首先要判断 nums[0] = 2 是否在 map 中,如果不存在,那么插入键值对 key = 9 - 2 = 7, value = 0,之后当 i = 1 时,此时判断 nums[1] = 7 已存在于 map 中,那么取出该 value = 0 作为第一个返回值,当前 i 作为第二个返回值,具体代码如下所示。

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public int[] twoSum(int[] nums, int target) {
int len = nums.length;
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < len; ++i) {
if (map.containsKey(nums[i])) {
return new int[]{map.get(nums[i]), i};
}
map.put(target - nums[i], i);
}
return null;
}
}

002 Add Two Numbers

Description

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example

1
2
3
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

Tags: Linked List, Math

思路

题意我也是看了好久才看懂,就是以链表表示一个数,低位在前,高位在后,所以题中的例子就是 342 + 465 = 807,所以我们模拟计算即可。

1
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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode node = new ListNode(0);
ListNode n1 = l1, n2 = l2, t = node;
int sum = 0;
while (n1 != null || n2 != null) {
sum /= 10;
if (n1 != null) {
sum += n1.val;
n1 = n1.next;
}
if (n2 != null) {
sum += n2.val;
n2 = n2.next;
}
t.next = new ListNode(sum % 10);
t = t.next;
}
if (sum / 10 != 0) t.next = new ListNode(1);
return node.next;
}
}

003 Longest Substring Without Repeating Characters

Description

Given a string, find the length of the longest substring without repeating characters.

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

Tags: Hash Table, Two Pointers, String

思路

题意是计算不带重复字符的最长子字符串的长度,开辟一个 hash 数组来存储该字符上次出现的位置,比如 hash[a] = 3 就是代表 a 字符前一次出现的索引在 3,遍历该字符串,获取到上次出现的最大索引(只能向前,不能退后),与当前的索引做差获取的就是本次所需长度,从中迭代出最大值就是最终答案。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public int lengthOfLongestSubstring(String s) {
int len;
if (s == null || (len = s.length()) == 0) return 0;
int preP = 0, max = 0;
int[] hash = new int[128];
for (int i = 0; i < len; ++i) {
char c = s.charAt(i);
if (hash[c] > preP) {
preP = hash[c];
}
int l = i - preP + 1;
hash[c] = i + 1;
if (l > max) max = l;
}
return max;
}
}

004 Median of Two Sorted Arrays

Description

There are two sorted arrays nums1 and nums2 of size m and n respectively.

Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).

Example 1:

1
2
3
4
nums1 = [1, 3]
nums2 = [2]
The median is 2.0

Example 2:

1
2
3
4
nums1 = [1, 2]
nums2 = [3, 4]
The median is (2 + 3)/2 = 2.5

Tags: Array, Binary Search, Divide and Conquer

思路

题意是给你两个已排序的递增数组,让你找出其中位数。

乍一看这题并不是很难,因为两序列有序,所以我们很容想到时间复杂度为 O(m + n) 的做法:依次取出两数组中较小的元素,然后找到中间的元素即可。但这题要求的时间复杂度为 O(log(m + n)),那么我们自然而然地就能想到二分查找法进行求解。

题目是让找两数组的中位数,我们可以泛化为求两数组中第 k 大的元素,那么,求中位数就是其中的一个特例而已。helper 函数所起到的作用就是求两数组中第 k 大的元素,下面来解释其原理:

假设数组分别记为 AB,当前需要搜索第 k 大的数,于是我们可以考虑从数组 A 中取出前 m 个元素,从数组 B 中取出前 k - m 个元素。由于数组 AB 分别排序,则 A[m - 1] 大于从数组 A 中取出的其他所有元素,B[k - m - 1] 大于数组 B 中取出的其他所有元素。此时,尽管取出元素之间的相对大小关系不确定,但 A[m - 1]B[k - m - 1] 的较大者一定是这 k 个元素中最大的。那么,较小的那个元素一定不是第 k 大的,这里留给读者自己想象。

为叙述方便,假设 A[m - 1] 是较小的那个元素,那么我们可以把 A[0]A[1]A[m - 1] 排除掉,并且更新 k 值为 k - m,也就是下一次就是从剩余的元素中寻找第 k - m 大的元素,这样,我们就完成了一次范围缩小,同理进行下一轮的操作。

那么什么时候停止操作呢?分两种情况:

  1. 当某个数组的数都被取完了,那么直接返回另一个数组的后 k 个元素即可。

  2. k = 1 时,也就是只需再找一个数即可,也就是取两者当前较小的那个即可。

特别地,我们选取 m = k / 2,下面是我画的草图,希望能帮助大家理解。

借助上面的理论,你能写出相关代码了吗?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int len = nums1.length + nums2.length;
if (len % 2 == 0) {
return (helper(nums1, 0, nums2, 0, len / 2) + helper(nums1, 0, nums2, 0, len / 2 + 1)) / 2.0;
}
return helper(nums1, 0, nums2, 0, (len + 1) / 2);
}
private int helper(int[] nums1, int m, int[] nums2, int n, int k) {
if (m >= nums1.length) return nums2[n + k - 1];
if (n >= nums2.length) return nums1[m + k - 1];
if (k == 1) return Math.min(nums1[m], nums2[n]);
int p1 = m + k / 2 - 1;
int p2 = n + k / 2 - 1;
int mid1 = p1 < nums1.length ? nums1[p1] : Integer.MAX_VALUE;
int mid2 = p2 < nums2.length ? nums2[p2] : Integer.MAX_VALUE;
if (mid1 < mid2) {
return helper(nums1, m + k / 2, nums2, n, k - k / 2);
}
return helper(nums1, m, nums2, n + k / 2, k - k / 2);
}
}

005 Longest Palindromic Substring

Description

Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

Example:

1
2
3
4
5
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.

Example:

1
2
3
Input: "cbbd"
Output: "bb"

Tags: String

思路 0

题意是寻找出字符串中最长的回文串,所谓回文串就是正序和逆序相同的字符串,也就是关于中间对称。我们先用最常规的做法,依次去求得每个字符的最长回文,要注意每个字符有奇数长度的回文串和偶数长度的回文串两种情况,相信你可以很轻易地从如下代码中找到相关代码,记录最长回文的始末位置即可,时间复杂度的话,首先要遍历一遍字符串,然后对每个字符都去求得最长回文,所以时间复杂度为 O(n^2)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
int st, end;
public String longestPalindrome(String s) {
int len = s.length();
if (len <= 1) return s;
char[] chars = s.toCharArray();
for (int i = 0; i < len; i++) {
helper(chars, i, i);
helper(chars, i, i + 1);
}
return s.substring(st, end + 1);
}
private void helper(char[] chars, int l, int r) {
while (l >= 0 && r < chars.length && chars[l] == chars[r]) {
--l;
++r;
}
if (end - st < r - l - 2) {
st = l + 1;
end = r - 1;
}
}
}

思路 1

如果利用暴力法遍历所有字串是否回文的情况这道题肯定是 Time Limit Exceeded 的,那么我们是否可以把之前遍历的结果利用上呢,那么动态规划的想法就呼之欲出了,我们定义 dp[i][j] 的意思为字符串区间 [i, j] 是否为回文串,那么我们分三种情况:

  1. i == j 时,那么毫无疑问 dp[i][j] = true

  2. i + 1 == j 时,那么 dp[i][j] 的值取决于 s[i] == s[j]

  3. i + 1 < j 时,那么 dp[i][j] 的值取决于 dp[i + 1][j - 1] && s[i] == s[j]

根据以上的动态转移方程,我们的问题即可迎刃而解,时间复杂度的话显而易见,也是 O(n^2)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public String longestPalindrome(String s) {
int len = s.length();
if (len <= 1) return s;
int st = 0, end = 0;
char[] chars = s.toCharArray();
boolean[][] dp = new boolean[len][len];
for (int i = 0; i < len; i++) {
dp[i][i] = true;
for (int j = 0; j < i; j++) {
if (j + 1 == i) {
dp[j][i] = chars[j] == chars[i];
} else {
dp[j][i] = dp[j + 1][i - 1] && chars[j] == chars[i];
}
if (dp[j][i] && i - j > end - st) {
st = j;
end = i;
}
}
}
return s.substring(st, end + 1);
}
}

思路 2

马拉车算法(Manacher’s Algorithm)

背景

给定一个字符串,求出其最长回文子串(回文字符串就是从左到右读和从右往左读完全一样,也就是字符串关于中间对称)。例如:

  1. s = “babad”,最长回文长度为 3,可以是 bab 或者 aba

  2. s = “cbbda”,最长回文长度为 2,即 bb

  3. s = “abcde”,最长回文长度为 1,即单个字符本身。

这个问题等同于 LeetCode 上的 Longest Palindromic Substring,其相关题解可以查看这里:传送门

以上问题的传统思路大概是遍历每一个字符,以该字符为中心向两边查找,其时间复杂度为 O(n^2),效率很差。

1975 年,一个叫 Manacher 的人发明了 Manacher 算法(中文名:马拉车算法),该算法可以把时间复杂度提升到 O(n),下面我以我理解的思路来讲解其原理。

分析

由于回文串的奇偶行不确定,比如 lol 是奇回文,而 lool 是偶回文,马拉车算法的第一步就是对其进行预处理,做法就是在每个字符两侧都加上一个特殊字符,一般就是不会出现在原串中的即可,我们可以选取 #,那么

1
2
lol -> #l#o#l#
lool -> #l#o#o#l#

这样处理后,不管原来字符串长度是奇数还是偶数,最终得到的长度都将是奇数,从而能把两种情况合并起来一起考虑,记预处理后的字符串为 str

我们把一个回文串中最左或最右位置的字符与其对称轴的距离称为回文半径。

马拉车算法定义了一个回文半径数组 len,用 len[i] 表示以第 i 个字符为对称轴的回文串的回文半径,比如以 str[i] 为中心的最长回文串是 str[l, r],那么 len[i] = r - i + 1

我们以 lollool 为例,参看下表。

str # l # o # l # l # o # o # l #
len[] 1 2 1 4 l 2 5 2 1 2 5 2 1 2 1

可以发现 len[i] - 1 就等于该回文串在原串中的长度。

证明:在转换后的字符串 str 中,那么对于以 str[i] 为中心的最长回文串的长度为 2 * len[i] - 1,其中又有 len[i] 个分隔符,所以在原字符串中的回文串长度就是 len[i] - 1

那么我们剩下的工作就是求 len 数组。

为了防止数组越界,我们在首位再加上非 # 的不常用字符,比如 ~,那么 lollool 就表示为 ~#l#o#l#l#o#o#l#~,这样我们就省去写很多 if else 的边界处理。

我们先看一张图,如下所示:

006 ZigZag Conversion

Description

The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)

1
2
3
P A H N
A P L S I I G
Y I R

And then read line by line: "PAHNAPLSIIGYIR"

Write the code that will take a string and make this conversion given a number of rows:

1
string convert(string text, int nRows);

convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".

Tags: String

思路 0

题意是让你把字符串按波浪形排好,然后返回横向读取的字符串。

听不懂的话,看下面的表示应该就明白了:

1
2
3
4
5
6
7
0 2n-2 4n-4
1 2n-3 2n-1 4n-5 4n-5
2 2n-4 2n 4n-6 .
. . . . .
. n+1 . 3n-1 .
n-2 n 3n-4 3n-2 5n-6
n-1 3n-3 5n-5

那么我们可以根据上面找规律,可以看到波峰和波谷是单顶点的,它们周期是 2 * (n - 1),单独处理即可;中间的部分每个周期会出现两次,规律很好找,留给读者自己想象,不懂的可以结合以下代码。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public String convert(String s, int numRows) {
if (numRows <= 1) return s;
int len = s.length();
char[] chars = s.toCharArray();
int cycle = 2 * (numRows - 1);
StringBuilder sb = new StringBuilder();
for (int j = 0; j < len; j += cycle) {
sb.append(chars[j]);
}
for (int i = 1; i < numRows - 1; i++) {
int step = 2 * i;
for (int j = i; j < len; j += step) {
sb.append(chars[j]);
step = cycle - step;
}
}
for (int j = numRows - 1; j < len; j += cycle) {
sb.append(chars[j]);
}
return sb.toString();
}
}

思路 1

另外一种思路就是开辟相应行数的 StringBuilder 对象,然后模拟波浪生成的样子分别插入到相应的 StringBuilder 对象,比较直白简单,具体代码如下。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public String convert(String s, int numRows) {
if (numRows <= 1) return s;
int len = s.length();
char[] chars = s.toCharArray();
StringBuilder[] sbs = new StringBuilder[numRows];
for (int i = 0; i < numRows; i++) {
sbs[i] = new StringBuilder();
}
int i = 0;
while (i < len) {
for (int j = 0; j < numRows && i < len; ++j) {
sbs[j].append(chars[i++]);
}
for (int j = numRows - 2; j >= 1 && i < len; --j) {
sbs[j].append(chars[i++]);
}
}
for (i = 1; i < numRows; i++) {
sbs[0].append(sbs[i]);
}
return sbs[0].toString();
}
}

007 Reverse Integer

Description

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

1
2
Input: 123
Output: 321

Example 2:

1
2
Input: -123
Output: -321

Example 3:

1
2
Input: 120
Output: 21

Note:

Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

Tags: Math

思路

题意是给你一个整型数,求它的逆序整型数,而且有个小坑点,当它的逆序整型数溢出的话,那么就返回 0,用我们代码表示的话可以求得结果保存在 long 中,最后把结果和整型的两个范围比较即可。

1
2
3
4
5
6
7
8
class Solution {
public int reverse(int x) {
long res = 0;
for (; x != 0; x /= 10)
res = res * 10 + x % 10;
return res > Integer.MAX_VALUE || res < Integer.MIN_VALUE ? 0 : (int) res;
}
}

008 String to Integer (atoi)

Description

Implement atoi to convert a string to an integer.

Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

Spoilers:

Requirements for atoi:

The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.

The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.

If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.

Tags: Math, String

思路

题意是把一个字符串转为整型,但要注意所给的要求,先去除最前面的空格,然后判断正负数,注意正数可能包含 +,如果之后存在非数字或全为空则返回 0,而如果合法的值超过 int 表示的最大范围,则根据正负号返回 INT_MAXINT_MIN

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public int myAtoi(String str) {
int i = 0, ans = 0, sign = 1, len = str.length();
while (i < len && str.charAt(i) == ' ') ++i;
if (i < len && (str.charAt(i) == '-' || str.charAt(i) == '+')) {
sign = str.charAt(i++) == '+' ? 1 : -1;
}
for (; i < len; ++i) {
int tmp = str.charAt(i) - '0';
if (tmp < 0 || tmp > 9)
break;
if (ans > Integer.MAX_VALUE / 10 || ans == Integer.MAX_VALUE / 10 && Integer.MAX_VALUE % 10 < tmp)
return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
else
ans = ans * 10 + tmp;
}
return sign * ans;
}
}

009 Palindrome Number

Description

Determine whether an integer is a palindrome. Do this without extra space.

Spoilers:

Some hints:

Could negative integers be palindromes? (ie, -1)

If you are thinking of converting the integer to string, note the restriction of using extra space.

You could also try reversing an integer. However, if you have solved the problem “Reverse Integer”, you know that the reversed integer might overflow. How would you handle such case?

There is a more generic way of solving this problem.

Tags: Math

思路 0

题意是判断一个有符号整型数是否是回文,也就是逆序过来的整数和原整数相同,首先负数肯定不是,接下来我们分析一下最普通的解法,就是直接算出他的回文数,然后和给定值比较即可。

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public boolean isPalindrome(int x) {
if (x < 0) return false;
int copyX = x, reverse = 0;
while (copyX > 0) {
reverse = reverse * 10 + copyX % 10;
copyX /= 10;
}
return x == reverse;
}
}

思路 1

好好思考下是否需要计算整个长度,比如 1234321,其实不然,我们只需要计算一半的长度即可,就是在计算过程中的那个逆序数比不断除 10 的数大就结束计算即可,但是这也带来了另一个问题,比如 10 的倍数的数 10010,它也会返回 true,所以我们需要对 10 的倍数的数再加个判断即可,代码如下所示。

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public boolean isPalindrome(int x) {
if (x < 0 || (x != 0 && x % 10 == 0)) return false;
int halfReverseX = 0;
while (x > halfReverseX) {
halfReverseX = halfReverseX * 10 + x % 10;
x /= 10;
}
return halfReverseX == x || halfReverseX / 10 == x;
}
}

010 Regular Expression Matching

Description

Implement regular expression matching with support for '.' and '*'.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
'.' Matches any single character.
'*' Matches zero or more of the preceding element.
The matching should cover the entire input string (not partial).
The function prototype should be:
bool isMatch(const char *s, const char *p)
Some examples:
isMatch("aa", "a") → false
isMatch("aa", "aa") → true
isMatch("aaa", "aa") → false
isMatch("aa", "a*") → true
isMatch("aa", ".*") → true
isMatch("ab", ".*") → true
isMatch("aab", "c*a*b") → true

Tags: String, Dynamic Programming, Backtracking

思路 0

题意是让让你从判断 s 字符串是否正则匹配于 p,这道题和 [Wildcard Matching][044] 很是相似,区别在于 *,通配符的 * 是可以随意出现的,跟前面字符没有任何关系,其作用是可以表示任意字符串;而正则匹配的 * 不能单独存在,前面必须具有一个字符,其意义是表明前面的这个字符个数可以是任意个数,包括 0 个。首先我们用递归的方式来实现,其思路如下:

  • 如果 sp 都为空,那么返回 true

  • 如果 p 的长度为 1,当 s 的长度也为 1,并且他们首位匹配则返回 true,否则返回 false

  • 如果 p 的第二个字符不为 ‘*’,如果 s 为空,那就返回 false,首位匹配则返回递归调用他们去掉首位的子字符串,否则返回 false

  • 如果 p 的第二个字符为 ‘*’,循环当 s 不为空,且首位匹配,如果递归调用是否匹配 s 字符串和 p 去掉前两位的子字符串,则返回 true,否则 s 去掉首字母继续循环;

  • 返回递归调用 s 字符串和 p 去掉前两位的子字符串是否匹配。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public boolean isMatch(String s, String p) {
if (p.isEmpty()) return s.isEmpty();
if (p.length() == 1) {
return s.length() == 1 && (p.charAt(0) == s.charAt(0) || p.charAt(0) == '.');
}
if (p.charAt(1) != '*') {
if (s.isEmpty()) return false;
return (p.charAt(0) == s.charAt(0) || p.charAt(0) == '.')
&& isMatch(s.substring(1), p.substring(1));
}
// match 1 or more preceding element
while (!s.isEmpty() && (p.charAt(0) == s.charAt(0) || p.charAt(0) == '.')) {
if (isMatch(s, p.substring(2))) return true;
s = s.substring(1);
}
// match 0 preceding element
return isMatch(s, p.substring(2));
}
}

思路 1

我们可以把上面的思路更简单化,如下:

  • 如果 sp 都为空,那么返回 true

  • 如果 p 的第二个字符为 *,由于 * 前面的字符个数可以为任意,那么我们先递归调用个数为 0 的情况;或者当 s 不为空,如果他们的首字母匹配,那么我们就递归调用去掉去掉首字母的 s 和完整的 p

  • 如果 p 的第二个字符不为 *,那么我们就老老实实判断第一个字符是否匹配并且递归调用他们去掉首位的子字符串。

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public boolean isMatch(String s, String p) {
if (p.isEmpty()) return s.isEmpty();
if (p.length() > 1 && p.charAt(1) == '*') {
return isMatch(s, p.substring(2))
|| (!s.isEmpty() && (p.charAt(0) == s.charAt(0) || p.charAt(0) == '.')
&& isMatch(s.substring(1), p));
}
return !s.isEmpty() && (p.charAt(0) == s.charAt(0) || p.charAt(0) == '.')
&& isMatch(s.substring(1), p.substring(1));
}
}

思路 2

另一种思路就是动态规划了,我们定义 dp[i][j] 的真假来表示 s[0..i) 是否匹配 p[0..j),通过思路 1,我们可以确定其状态转移方程如下所示:

  • 如果 p[j - 1] == '*', dp[i][j] = dp[i][j - 2] || (pc[j - 2] == sc[i - 1] || pc[j - 2] == '.') && dp[i - 1][j];

  • 如果 p[j - 1] != '*'dp[i][j] = dp[i - 1][j - 1] && (pc[j - 1] == '.' || pc[j - 1] == sc[i - 1]);

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public boolean isMatch(String s, String p) {
if (p.length() == 0) return s.length() == 0;
int sL = s.length(), pL = p.length();
boolean[][] dp = new boolean[sL + 1][pL + 1];
char[] sc = s.toCharArray(), pc = p.toCharArray();
dp[0][0] = true;
for (int i = 2; i <= pL; ++i) {
if (pc[i - 1] == '*' && dp[0][i - 2]) {
dp[0][i] = true;
}
}
for (int i = 1; i <= sL; ++i) {
for (int j = 1; j <= pL; ++j) {
if (pc[j - 1] == '*') {
dp[i][j] = dp[i][j - 2] || (pc[j - 2] == sc[i - 1] || pc[j - 2] == '.') && dp[i - 1][j];
} else {
dp[i][j] = dp[i - 1][j - 1] && (pc[j - 1] == '.' || pc[j - 1] == sc[i - 1]);
}
}
}
return dp[sL][pL];
}
}

011 Container With Most Water

Description

Given n non-negative integers a1, a2, …, an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.

Note: You may not slant the container and n is at least 2.

Tags: Array, Two Pointers

思路

题意是给你 a1, a2, …, ann 个数,代表 (i, ai) 坐标,让你从中找两个点与 x 轴围成的容器可以容纳最多的水。

不明白的话可以看数据为 1 8 6 2 5 4 8 3 7 所示的图。

如果用暴力法求每种情况的结果,其时间复杂度为 O(n^2),相信肯定会超时,我们可以探索下是否有更巧妙的办法呢,题目的标签有双指针,是否就可以想到首尾各放一指针,然后根据条件来收缩。首先计算一次首尾构成的最大面积,然后分析下该移动哪个指针,如果移动大的那个指针的话,那样只会减小面积,所以我们要移动小的那个指针,小的那个指针移动到哪呢?当然是移动到大于之前的值的地方,否则面积不都比之前小么,然后继续更新最大值即可,借助如上分析写出如下代码应该不是什么难事了吧。

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public int maxArea(int[] height) {
int l = 0, r = height.length - 1;
int max = 0, h = 0;
while (l < r) {
h = Math.min(height[l], height[r]);
max = Math.max(max, (r - l) * h);
while (height[l] <= h && l < r) ++l;
while (height[r] <= h && l < r) --r;
}
return max;
}
}

012 Integer to Roman

Description

Given an integer, convert it to a roman numeral.

Input is guaranteed to be within the range from 1 to 3999.

Tags: Math, String

思路

题意是整型数转罗马数字,范围从 1 到 3999,查看下百度百科的罗马数字介绍如下:

  • 相同的数字连写,所表示的数等于这些数字相加得到的数,如 Ⅲ=3;

  • 小的数字在大的数字的右边,所表示的数等于这些数字相加得到的数,如 Ⅷ=8、Ⅻ=12;

  • 小的数字(限于 Ⅰ、X 和 C)在大的数字的左边,所表示的数等于大数减小数得到的数,如 Ⅳ=4、Ⅸ=9。

那么我们可以把整数的每一位分离出来,让其每一位都用相应的罗马数字位表示,最终拼接完成。比如 621 我们可以分离百、十、个分别为 621,那么 600 对应的罗马数字是 DC20 对应的罗马数字是 XX1 对应的罗马数字是 I,所以最终答案便是 DCXXI

1
2
3
4
5
6
7
8
9
class Solution {
public String intToRoman(int num) {
String M[] = {"", "M", "MM", "MMM"};
String C[] = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
String X[] = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
String I[] = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};
return M[num / 1000] + C[(num % 1000) / 100] + X[(num % 100) / 10] + I[num % 10];
}
}

013 Roman to Integer

Description

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

Tags: Math, String

思路

题意是罗马数字转整型数,范围从 1 到 3999,查看下百度百科的罗马数字介绍如下:

  • 相同的数字连写,所表示的数等于这些数字相加得到的数,如 Ⅲ=3;

  • 小的数字在大的数字的右边,所表示的数等于这些数字相加得到的数,如 Ⅷ=8、Ⅻ=12;

  • 小的数字(限于 Ⅰ、X 和 C)在大的数字的左边,所表示的数等于大数减小数得到的数,如 Ⅳ=4、Ⅸ=9。

那么我们可以利用 map 来完成罗马数字的 7 个数字符号:I、V、X、L、C、D、M 和整数的映射关系,然后根据上面的解释来模拟完成即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public int romanToInt(String s) {
Map<Character, Integer> map = new HashMap<>();
map.put('I', 1);
map.put('V', 5);
map.put('X', 10);
map.put('L', 50);
map.put('C', 100);
map.put('D', 500);
map.put('M', 1000);
int len = s.length();
int sum = map.get(s.charAt(len - 1));
for (int i = len - 2; i >= 0; --i) {
if (map.get(s.charAt(i)) < map.get(s.charAt(i + 1))) {
sum -= map.get(s.charAt(i));
} else {
sum += map.get(s.charAt(i));
}
}
return sum;
}
}

014 Longest Common Prefix

Description

Write a function to find the longest common prefix string amongst an array of strings.

Tags: String

思路

题意是让你从字符串数组中找出公共前缀,我的想法是找出最短的那个字符串的长度 minLen,然后在 0...minLen 的范围比较所有字符串,如果比较到有不同的字符,那么直接返回当前索引长度的字符串即可,否则最后返回最短的字符串即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public String longestCommonPrefix(String[] strs) {
int len = strs.length;
if (len == 0) return "";
int minLen = 0x7fffffff;
for (String str : strs) minLen = Math.min(minLen, str.length());
for (int j = 0; j < minLen; ++j)
for (int i = 1; i < len; ++i)
if (strs[0].charAt(j) != strs[i].charAt(j))
return strs[0].substring(0, j);
return strs[0].substring(0, minLen);
}
}

015 3Sum

Description

Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note: The solution set must not contain duplicate triplets.

1
2
3
4
5
6
7
For example, given array S = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]

Tags: Array, Two Pointers

思路

题意是让你从数组中找出所有三个和为 0 的元素构成的非重复序列,这样的话我们可以把数组先做下排序,然后遍历这个排序数组,用两个指针分别指向当前元素的下一个和数组尾部,判断三者的和与 0 的大小来移动两个指针,其中细节操作就是优化和去重。

1
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
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> list = new ArrayList<>();
int len = nums.length;
if (len < 3) return list;
Arrays.sort(nums);
int max = nums[len - 1];
if (max < 0) return list;
for (int i = 0; i < len - 2; ) {
if (nums[i] > 0) break;
if (nums[i] + 2 * max < 0) {
while (nums[i] == nums[++i] && i < len - 2) ;
continue;
}
int left = i + 1, right = len - 1;
while (left < right) {
int sum = nums[i] + nums[left] + nums[right];
if (sum == 0) {
list.add(Arrays.asList(nums[i], nums[left], nums[right]));
while (nums[left] == nums[++left] && left < right) ;
while (nums[right] == nums[--right] && left < right) ;
} else if (sum < 0) ++left;
else --right;
}
while (nums[i] == nums[++i] && i < len - 2) ;
}
return list;
}
}

016 3Sum Closest

Description

Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

1
2
3
For example, given array S = {-1 2 1 -4}, and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

Tags: Array, Two Pointers

思路

题意是让你从数组中找出最接近 target 的三个数的和,该题和 [3Sum][015] 的思路基本一样,先对数组进行排序,然后遍历这个排序数组,用两个指针分别指向当前元素的下一个和数组尾部,判断三者的和与 target 的差值来移动两个指针,并更新其结果,当然,如果三者的和直接与 target 值相同,那么返回 target 结果即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class Solution {
public int threeSumClosest(int[] nums, int target) {
int delta = 0x7fffffff, res = 0;
Arrays.sort(nums);
int len = nums.length - 2;
for (int i = 0; i < len; i++) {
int left = i + 1, right = nums.length - 1;
while (left < right) {
int sum = nums[i] + nums[left] + nums[right];
int curDelta = Math.abs(sum - target);
if (curDelta == 0) return sum;
if (curDelta < delta) {
delta = curDelta;
res = sum;
}
if (sum > target) --right;
else ++left;
}
}
return res;
}
}

017 Letter Combinations of a Phone Number

Description

Given a digit string, return all possible letter combinations that the number could represent.

A mapping of digit to letters (just like on the telephone buttons) is given below.

img

1
2
Input:Digit string "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

Note:

Although the above answer is in lexicographical order, your answer could be in any order you want.

Tags: String, Backtracking

思路 0

题意是给你按键,让你组合出所有不同结果,首先想到的肯定是回溯了,对每个按键的所有情况进行回溯,回溯的终点就是结果字符串长度和按键长度相同。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
private static String[] map = new String[]{"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
public List<String> letterCombinations(String digits) {
if (digits.length() == 0) return Collections.emptyList();
List<String> list = new ArrayList<>();
helper(list, digits, "");
return list;
}
private void helper(List<String> list, String digits, String ans) {
if (ans.length() == digits.length()) {
list.add(ans);
return;
}
for (char c : map[digits.charAt(ans.length()) - '2'].toCharArray()) {
helper(list, digits, ans + c);
}
}
}

思路 1

还有一种思路就是利用队列,根据上一次队列中的值,该值拼接当前可选值来不断迭代其结果,具体代码如下。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
private static String[] map = new String[]{"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
public List<String> letterCombinations(String digits) {
if (digits.length() == 0) return Collections.emptyList();
LinkedList<String> list = new LinkedList<>();
list.add("");
char[] charArray = digits.toCharArray();
for (int i = 0; i < charArray.length; i++) {
char c = charArray[i];
while (list.getFirst().length() == i) {
String pop = list.removeFirst();
for (char v : map[c - '2'].toCharArray()) {
list.addLast(pop + v);
}
}
}
return list;
}
}

018 4Sum

Description

Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

Note: The solution set must not contain duplicate quadruplets.

1
2
3
4
5
6
7
8
For example, given array S = [1, 0, -1, 0, -2, 2], and target = 0.
A solution set is:
[
[-1, 0, 0, 1],
[-2, -1, 1, 2],
[-2, 0, 0, 2]
]

Tags: Array, Hash Table, Two Pointers

思路 0

题意是让你从数组中找出所有四个数的和为 target 的元素构成的非重复序列,该题和 [3Sum][015] 的思路基本一样,先对数组进行排序,然后遍历这个排序数组,因为这次是四个元素的和,所以外层需要两重循环,然后还是用两个指针分别指向当前元素的下一个和数组尾部,判断四者的和与 target 的大小来移动两个指针,其中细节操作还是优化和去重。

1
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
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> res = new ArrayList<>();
int len = nums.length;
if (len < 4) return res;
Arrays.sort(nums);
int max = nums[len - 1];
if (4 * max < target) return res;
for (int i = 0; i < len - 3;) {
if (nums[i] * 4 > target) break;
if (nums[i] + 3 * max < target) {
while (nums[i] == nums[++i] && i < len - 3) ;
continue;
}
for (int j = i + 1; j < len - 2;) {
int subSum = nums[i] + nums[j];
if (nums[i] + nums[j] * 3 > target) break;
if (subSum + 2 * max < target) {
while (nums[j] == nums[++j] && j < len - 2) ;
continue;
}
int left = j + 1, right = len - 1;
while (left < right) {
int sum = subSum + nums[left] + nums[right];
if (sum == target) {
res.add(Arrays.asList(nums[i], nums[j], nums[left], nums[right]));
while (nums[left] == nums[++left] && left < right);
while (nums[right] == nums[--right] && left < right);
} else if (sum < target) ++left;
else --right;
}
while (nums[j] == nums[++j] && j < len - 2) ;
}
while (nums[i] == nums[++i] && i < len - 3) ;
}
return res;
}
}

思路 1

从 [Two Sum][001]、[3Sum][015] 到现在的 4Sum,其实都是把高阶降为低阶,那么我们就可以写出 kSum 的函数来对其进行降阶处理,降到 2Sum 后那么我们就可以对其进行最后的判断了,代码如下所示,其也做了相应的优化和去重。

1
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
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
Arrays.sort(nums);
int len = nums.length;
if (len < 4) return Collections.emptyList();
int max = nums[len - 1];
if (4 * max < target) return Collections.emptyList();
return kSum(nums, 0, 4, target);
}
private List<List<Integer>> kSum(int[] nums, int start, int k, int target) {
List<List<Integer>> res = new ArrayList<>();
if (k == 2) {
int left = start, right = nums.length - 1;
while (left < right) {
int sum = nums[left] + nums[right];
if (sum == target) {
List<Integer> twoSum = new LinkedList<>();
twoSum.add(nums[left]);
twoSum.add(nums[right]);
res.add(twoSum);
while (nums[left] == nums[++left] && left < right) ;
while (nums[right] == nums[--right] && left < right) ;
} else if (sum < target) ++left;
else --right;
}
} else {
int i = start, end = nums.length - (k - 1), max = nums[nums.length - 1];
while (i < end) {
if (nums[i] * k > target) return res;
if (nums[i] + (k - 1) * max < target) {
while (nums[i] == nums[++i] && i < end) ;
continue;
}
List<List<Integer>> temp = kSum(nums, i + 1, k - 1, target - nums[i]);
for (List<Integer> t : temp) {
t.add(0, nums[i]);
}
res.addAll(temp);
while (nums[i] == nums[++i] && i < end) ;
}
}
return res;
}
}

019 Remove Nth Node From End of List

Description

Given a linked list, remove the nth node from the end of list and return its head.

For example,

1
2
3
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.

Note:

Given n will always be valid.

Try to do this in one pass.

Tags: Linked List, Two Pointers

思路

题意是让你删除链表中的倒数第 n 个数,我的解法是利用双指针,这两个指针相差 n 个元素,当后面的指针扫到链表末尾的时候,自然它前面的那个指针所指向的下一个元素就是要删除的元素,即 pre.next = pre.next.next;,但是如果一开始后面的指针指向的为空,此时代表的意思就是要删除第一个元素,即 head = head.next;

1
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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode pre = head;
ListNode afterPreN = head;
while (n-- != 0) {
afterPreN = afterPreN.next;
}
if (afterPreN != null) {
while (afterPreN.next != null) {
pre = pre.next;
afterPreN = afterPreN.next;
}
pre.next = pre.next.next;
} else {
head = head.next;
}
return head;
}
}

020 Valid Parentheses

Description

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

Tags: Stack, String

思路

题意是判断括号匹配是否正确,很明显,我们可以用栈来解决这个问题,当出现左括号的时候入栈,当遇到右括号时,判断栈顶的左括号是否何其匹配,不匹配的话直接返回 false 即可,最终判断是否空栈即可,这里我们可以用数组模拟栈的操作使其操作更快,有个细节注意下 top = 1;,从而省去了之后判空的操作和 top - 1 导致数组越界的错误。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public boolean isValid(String s) {
char[] stack = new char[s.length() + 1];
int top = 1;
for (char c : s.toCharArray()) {
if (c == '(' || c == '[' || c == '{') {
stack[top++] = c;
} else if (c == ')' && stack[--top] != '(') {
return false;
} else if (c == ']' && stack[--top] != '[') {
return false;
} else if (c == '}' && stack[--top] != '{') {
return false;
}
}
return top == 1;
}
}

021 Merge Two Sorted Lists

Description

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

Example:

1
2
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

Tags: Linked List

思路

题意是用一个新链表来合并两个已排序的链表,那我们只需要从头开始比较已排序的两个链表,新链表指针每次指向值小的节点,依次比较下去,最后,当其中一个链表到达了末尾,我们只需要把新链表指针指向另一个没有到末尾的链表此时的指针即可。

1
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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode head = new ListNode(0);
ListNode temp = head;
while (l1 != null && l2 != null) {
if (l1.val < l2.val) {
temp.next = l1;
l1 = l1.next;
} else {
temp.next = l2;
l2 = l2.next;
}
temp = temp.next;
}
temp.next = l1 != null ? l1 : l2;
return head.next;
}
}

022 Generate Parentheses

Description

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

For example, given n = 3, a solution set is:

1
2
3
4
5
6
7
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]

Tags: String, Backtracking

思路 0

题意是给你 n 值,让你找到所有格式正确的圆括号匹配组,题目中已经给出了 n = 3 的所有结果。遇到这种问题,第一直觉就是用到递归或者堆栈,我们选取递归来解决,也就是 helper 函数的功能,从参数上来看肯定很好理解了,leftRest 代表还有几个左括号可以用,rightNeed 代表还需要几个右括号才能匹配,初始状态当然是 rightNeed = 0, leftRest = n,递归的终止状态就是 rightNeed == 0 && leftRest == 0,也就是左右括号都已匹配完毕,然后把 str 加入到链表中即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public List<String> generateParenthesis(int n) {
List<String> list = new ArrayList<>();
helper(list, "", 0, n);
return list;
}
private void helper(List<String> list, String str, int rightNeed, int leftRest) {
if (rightNeed == 0 && leftRest == 0) {
list.add(str);
return;
}
if (rightNeed > 0) helper(list, str + ")", rightNeed - 1, leftRest);
if (leftRest > 0) helper(list, str + "(", rightNeed + 1, leftRest - 1);
}
}

思路 1

另一种实现方式就是迭代的思想了,我们来找寻其规律如下所示:

1
2
3
4
5
6
7
8
f(0): “”
f(1): “(“f(0)”)”
f(2): "(“f(0)”)"f(1), “(“f(1)”)”
f(3): "(“f(0)”)"f(2), "(“f(1)”)"f(1), “(“f(2)”)”
...

可以递推出 f(n) = "(“f(0)”)"f(n-1) , "(“f(1)”)"f(n-2) "(“f(2)”)"f(n-3) … "(“f(i)”)“f(n-1-i) … “(f(n-1)”)”

根据如上递推式写出如下代码应该不难了吧。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public List<String> generateParenthesis(int n) {
HashMap<Integer, List<String>> hashMap = new HashMap<>();
hashMap.put(0, Collections.singletonList(""));
for (int i = 1; i <= n; i++) {
List<String> list = new ArrayList<>();
for (int j = 0; j < i; j++) {
for (String fj : hashMap.get(j)) {
for (String fi_j_1 : hashMap.get(i - j - 1)) {
list.add("(" + fj + ")" + fi_j_1);// calculate f(i)
}
}
}
hashMap.put(i, list);
}
return hashMap.get(n);
}
}

023 Merge k Sorted Lists

Description

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

Tags: Linked List, Divide and Conquer, Heap

思路 0

题意是合并多个已排序的链表,分析并描述其复杂度,我们可以用分治法来两两合并他们,假设 k 为总链表个数,N 为总元素个数,那么其时间复杂度为 O(Nlogk)

1
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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
if (lists.length == 0) return null;
return helper(lists, 0, lists.length - 1);
}
private ListNode helper(ListNode[] lists, int left, int right) {
if (left >= right) return lists[left];
int mid = left + right >>> 1;
ListNode l0 = helper(lists, left, mid);
ListNode l1 = helper(lists, mid + 1, right);
return merge2Lists(l0, l1);
}
private ListNode merge2Lists(ListNode l0, ListNode l1) {
ListNode node = new ListNode(0), tmp = node;
while (l0 != null && l1 != null) {
if (l0.val <= l1.val) {
tmp.next = new ListNode(l0.val);
l0 = l0.next;
} else {
tmp.next = new ListNode(l1.val);
l1 = l1.next;
}
tmp = tmp.next;
}
tmp.next = l0 != null ? l0 : l1;
return node.next;
}
}

思路 1

还有另一种思路是利用优先队列,该数据结构用到的是堆排序,所以对总链表个数为 k 的复杂度为 logk,总元素为个数为 N 的话,其时间复杂度也为 O(Nlogk)

1
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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
if (lists.length == 0) return null;
PriorityQueue<ListNode> queue = new PriorityQueue<>(lists.length, new Comparator<ListNode>() {
@Override
public int compare(ListNode o1, ListNode o2) {
if (o1.val < o2.val) return -1;
else if (o1.val == o2.val) return 0;
else return 1;
}
});
ListNode node = new ListNode(0), tmp = node;
for (ListNode l : lists) {
if (l != null) queue.add(l);
}
while (!queue.isEmpty()) {
tmp.next = queue.poll();
tmp = tmp.next;
if (tmp.next != null) queue.add(tmp.next);
}
return node.next;
}
}

024 Swap Nodes in Pairs

Description

Given a linked list, swap every two adjacent nodes and return its head.

For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

Tags: Linked List

思路 0

题意是让你交换链表中相邻的两个节点,最终返回交换后链表的头,限定你空间复杂度为 O(1)。我们可以用递归来算出子集合的结果,递归的终点就是指针指到链表末少于两个元素时,如果不是终点,那么我们就对其两节点进行交换,这里我们需要一个临时节点来作为交换桥梁,就不多说了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) return head;
ListNode node = head.next;
head.next = swapPairs(node.next);
node.next = head;
return node;
}
}

思路 1

另一种实现方式就是用循环来实现了,两两交换节点,也需要一个临时节点来作为交换桥梁,直到当前指针指到链表末少于两个元素时停止,代码很简单,如下所示。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode preHead = new ListNode(0), cur = preHead;
preHead.next = head;
while (cur.next != null && cur.next.next != null) {
ListNode temp = cur.next.next;
cur.next.next = temp.next;
temp.next = cur.next;
cur.next = temp;
cur = cur.next.next;
}
return preHead.next;
}
}

025 Reverse Nodes in k-Group

Description

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.

k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.

You may not alter the values in the nodes, only nodes itself may be changed.

Only constant memory is allowed.

For example,

Given this linked list: 1->2->3->4->5

For k = 2, you should return: 2->1->4->3->5

For k = 3, you should return: 3->2->1->4->5

Tags: Linked List

思路

题意是让你以 k 个元素为一组来翻转链表,最后不足 k 个的话不需要翻转,最传统的思路就是每遇到 k 个元素,对其 k 个元素进行翻转,而难点就是在此,下面介绍其原理,我们以例子中的 k = 3 为例,其 prenext 如下所示。

1
2
3
0->1->2->3->4->5
| |
pre next

我们要做的就是把 prenext 之间的元素逆序,思想是依次从第二个元素到第 k 个元素,依次把它插入到 pre 后面,过程如下。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
head move
| |
0->1->2->3->4->5
| |
pre next
head move
| |
0->2->1->3->4->5
| |
pre next
head move
| |
0->3->2->1->4->5
| |
pre next

好了,根据原理,那写出代码就不难了。

1
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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
if (head == null || k == 1) return head;
ListNode node = new ListNode(0), pre = node;
node.next = head;
for (int i = 1; head != null; ++i) {
if (i % k == 0) {
pre = reverse(pre, head.next);
head = pre.next;
} else {
head = head.next;
}
}
return node.next;
}
private ListNode reverse(ListNode pre, ListNode next) {
ListNode head = pre.next;
ListNode move = head.next;
while (move != next) {
head.next = move.next;
move.next = pre.next;
pre.next = move;
move = head.next;
}
return head;
}
}

026 Remove Duplicates from Sorted Array

Description

Given a sorted array, remove the duplicates in-place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

Example:

1
2
3
4
Given nums = [1,1,2],
Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.
It doesn't matter what you leave beyond the new length.

Tags: Array, Two Pointers

思路

题意是让你从一个有序的数组中移除重复的元素,并返回之后数组的长度。我的思路是判断长度小于等于 1 的话直接返回原长度即可,否则的话遍历一遍数组,用一个 tail 变量指向尾部,如果后面的元素和前面的元素不同,就让 tail 变量加一,最后返回 tail 即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public int removeDuplicates(int[] nums) {
int len = nums.length;
if (len <= 1) return len;
int tail = 1;
for (int i = 1; i < len; ++i) {
if (nums[i - 1] != nums[i]) {
nums[tail++] = nums[i];
}
}
return tail;
}
}

027 Remove Element

Description

Given an array and a value, remove all instances of that value in-place and return the new length.

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

The order of elements can be changed. It doesn’t matter what you leave beyond the new length.

Example:

1
2
3
Given nums = [3,2,2,3], val = 3,
Your function should return length = 2, with the first two elements of nums being 2.

Tags: Array, Two Pointers

思路

题意是移除数组中值等于 val 的元素,并返回之后数组的长度,并且题目中指定空间复杂度为 O(1),我的思路是用 tail 标记尾部,遍历该数组时当索引元素不等于 val 时,tail 加一,尾部指向当前元素,最后返回 tail 即可。

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public int removeElement(int[] nums, int val) {
int tail = 0;
for (int i = 0, len = nums.length; i < len; ++i) {
if (nums[i] != val) {
nums[tail++] = nums[i];
}
}
return tail;
}
}

028 Implement strStr()

Description

Implement strStr().

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Example 1:

1
2
Input: haystack = "hello", needle = "ll"
Output: 2

Example 2:

1
2
Input: haystack = "aaaaa", needle = "bba"
Output: -1

Tags:** Two Pointers, String

思路

题意是从主串中找到子串的索引,如果找不到则返回-1,当子串长度大于主串,直接返回-1,然后我们只需要遍历比较即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public int strStr(String haystack, String needle) {
int l1 = haystack.length(), l2 = needle.length();
if (l1 < l2) return -1;
for (int i = 0; ; i++) {
if (i + l2 > l1) return -1;
for (int j = 0; ; j++) {
if (j == l2) return i;
if (haystack.charAt(i + j) != needle.charAt(j)) break;
}
}
}
}

029 Divide Two Integers

Description

Divide two integers without using multiplication, division and mod operator.

If it is overflow, return MAX_INT.

Tags: Math, Binary Search

思路

题意是让你算两个整型数相除后的结果,如果结果溢出就返回 MAX_INT,但不能使用乘、除、余的操作符,如果是用加减操作符的话肯定会超时哈,这样的话我们就只能想到位操作符了。

首先,我们分析下溢出的情况,也就是当被除数为 Integer.MIN_VALUE,除数为 -1 时会溢出,因为 |Integer.MIN_VALUE| = Integer.MAX_VALUE + 1

然后,我们把除数和被除数都转为 long 类型的正数去做下一步操作,我这里以 223 相除为例子,因为 22 >= 3,我们对 3 进行左移一位,也就是乘 2,结果为 6,比 22 小,我们继续对 6 左移一位结果为 12,还是比 22 小,我们继续对 12 左移一位为 24,比 22 大,这时我们可以分析出,22 肯定比 34 倍要大,4 是怎么来的?因为我们左移了两次,也就是 1 << 2 = 4,此时我们记下这个 4,然后让 22 - 3 * 4 = 10,因为 10 >= 3,对 103 进行同样的操作,我们可以得到 2,此时加上上次的 4,和为 6,也就是 2236 倍要大,此时还剩余 10 - 6 = 4,因为 4 >= 3,所以对 43 进行同样的操作,我们发现并不能对 3 进行左移了,因为 4 >= 3,所以 1 倍还是有的,所以加上最后的 1,结果为 6 + 1 = 7,也就是 22 整除 3 结果为 7

最终,我们对结果赋予符号位即可,根据以上思路来书写如下代码应该不是难事了吧。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public int divide(int dividend, int divisor) {
if (dividend == Integer.MIN_VALUE && divisor == -1) {
return Integer.MAX_VALUE;
}
long dvd = Math.abs((long) dividend);
long dvr = Math.abs((long) divisor);
int res = 0;
while (dvd >= dvr) {
long temp = dvr, multiple = 1;
while (dvd >= temp << 1) {
temp <<= 1;
multiple <<= 1;
}
dvd -= temp;
res += multiple;
}
return (dividend < 0) ^ (divisor < 0) ? -res : res;
}
}

033 Search in Rotated Sorted Array

Description

Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.

(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).

You are given a target value to search. If found in the array return its index, otherwise return -1.

You may assume no duplicate exists in the array.

Tags: Arrays, Binary Search

思路

题意是让你从一个旋转过后的递增序列中寻找给定值,找到返回索引,找不到返回-1,我们在下面这组数据中寻找规律。

1
2
3
4
5
6
1 2 4 5 6 7 0
2 4 5 6 7 0 1
4 5 6 7 0 1 2
5 6 7 0 1 2 4
6 7 0 1 2 4 5
7 0 1 2 4 5 6

由于是旋转一次,所以肯定有一半及以上的序列仍然是具有递增性质的,我们观察到如果中间的数比左面的数大的话,那么左半部分序列是递增的,否则右半部分就是递增的,那么我们就可以确定给定值是否在递增序列中,从而决定取舍哪半边。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public int search(int[] nums, int target) {
int l = 0, r = nums.length - 1, mid;
while (l <= r) {
mid = l + r >>> 1;
if (nums[mid] == target) return mid;
else if (nums[mid] >= nums[l]) {
if (nums[l] <= target && target < nums[mid]) r = mid - 1;
else l = mid + 1;
} else {
if (nums[mid] < target && target <= nums[r]) l = mid + 1;
else r = mid - 1;
}
}
return -1;
}
}

035 Search Insert Position

Description

Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

You may assume no duplicates in the array.

Example 1:

1
2
Input: [1,3,5,6], 5
Output: 2

Example 2:

1
2
Input: [1,3,5,6], 2
Output: 1

Example 3:

1
2
Input: [1,3,5,6], 7
Output: 4

Example 1:

1
2
Input: [1,3,5,6], 0
Output: 0

Tags: Array, Binary Search

思路

题意是让你从一个没有重复元素的已排序数组中找到插入位置的索引。因为数组已排序,所以我们可以想到二分查找法,因为查找到的条件是找到第一个等于或者大于 target 的元素的位置,所以二分法略作变动即可。

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public int searchInsert(int[] nums, int target) {
int left = 0, right = nums.length - 1, mid = (right + left) >> 1;
while (left <= right) {
if (target <= nums[mid]) right = mid - 1;
else left = mid + 1;
mid = (right + left) >> 1;
}
return left;
}
}

038 Count and Say

Description

The count-and-say sequence is the sequence of integers with the first five terms as following:

1
2
3
4
5
1. 1
2. 11
3. 21
4. 1211
5. 111221

1 is read off as "one 1" or 11.

11 is read off as "two 1s" or 21.

21 is read off as "one 2, then one 1" or 1211.

Given an integer n, generate the nth term of the count-and-say sequence.

Note: Each term of the sequence of integers will be represented as a string.

Example 1:

1
2
Input: 1
Output: "1"

Example 2:

1
2
Input: 4
Output: "1211"

Tags: String

思路

题意是数和说,根据如下序列 1, 11, 21, 1211, 111221, ...,求第 n 个数,规则很简单,就是数和说,数就是数这个数数字有几个,说就是说这个数,所以 1 就是 1 个 1:11,11 就是有 2 个 1:2121 就是 1 个 2、1 个 1:1211,可想而知后面就是 111221,思路的话就是按这个逻辑模拟出来即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public String countAndSay(int n) {
String str = "1";
while (--n > 0) {
int times = 1;
StringBuilder sb = new StringBuilder();
char[] chars = str.toCharArray();
int len = chars.length;
for (int j = 1; j < len; j++) {
if (chars[j - 1] == chars[j]) {
times++;
} else {
sb.append(times).append(chars[j - 1]);
times = 1;
}
}
str = sb.append(times).append(chars[len - 1]).toString();
}
return str;
}
}

043 Multiply Strings

Description

Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2.

Note:

  1. The length of both num1 and num2 is < 110.

  2. Both num1 and num2 contains only digits 0-9.

  3. Both num1 and num2 does not contain any leading zero.

  4. You must not use any built-in BigInteger library or convert the inputs to integer directly.

Tags: Math, String

思路

题意是让你计算两个非负字符串的乘积,我们模拟小学数学的方式来做,一位一位模拟计算,再各位累加。

1
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
class Solution {
public String multiply(String num1, String num2) {
if (num1.equals("0") || num2.equals("0")) return "0";
int l1 = num1.length(), l2 = num2.length(), l = l1 + l2;
char[] ans = new char[l];
char[] c1 = num1.toCharArray();
char[] c2 = num2.toCharArray();
for (int i = l1 - 1; i >= 0; --i) {
int c = c1[i] - '0';
for (int j = l2 - 1; j >= 0; --j) {
ans[i + j + 1] += c * (c2[j] - '0');
}
}
for (int i = l - 1; i > 0; ++i) {
if (ans[i] > 9) {
ans[i - 1] += ans[i] / 10;
ans[i] %= 10;
}
}
StringBuilder sb = new StringBuilder();
int i = 0;
for (; ; ++i) if (ans[i] != 0) break;
for (; i < ans.length; ++i) sb.append((char) (ans[i] + '0'));
return sb.toString();
}
}

044 Wildcard Matching

Description

Implement wildcard pattern matching with support for '?' and '*'.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
'?' Matches any single character.
'*' Matches any sequence of characters (including the empty sequence).
The matching should cover the entire input string (not partial).
The function prototype should be:
bool isMatch(const char *s, const char *p)
Some examples:
isMatch("aa","a") → false
isMatch("aa","aa") → true
isMatch("aaa","aa") → false
isMatch("aa", "*") → true
isMatch("aa", "a*") → true
isMatch("ab", "?*") → true
isMatch("aab", "c*a*b") → false

Tags: String, Dynamic Programming, Backtracking, Greedy

思路 0

题意是让让你从判断 s 字符串是否通配符匹配于 p,这道题和[Regular Expression Matching][010]很是相似,区别在于 *,正则匹配的 * 不能单独存在,前面必须具有一个字符,其意义是表明前面的这个字符个数可以是任意个数,包括 0 个;而通配符的 * 是可以随意出现的,跟前面字符没有任何关系,其作用是可以表示任意字符串。在此我们可以利用 贪心算法 来解决这个问题,需要两个额外指针 pmatch 来分别记录最后一个 * 的位置和 * 匹配到 s 字符串的位置,其贪心体现在如果遇到 *,那就尽可能取匹配后方的内容,如果匹配失败,那就回到上一个遇到 * 的位置来继续贪心。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public boolean isMatch(String s, String p) {
if (p.length() == 0) return s.length() == 0;
int si = 0, pi = 0, match = 0, star = -1;
int sl = s.length(), pl = p.length();
char[] sc = s.toCharArray(), pc = p.toCharArray();
while (si < sl) {
if (pi < pl && (pc[pi] == sc[si] || pc[pi] == '?')) {
si++;
pi++;
} else if (pi < pl && pc[pi] == '*') {
star = pi++;
match = si;
} else if (star != -1) {
si = ++match;
pi = star + 1;
} else return false;
}
while (pi < pl && pc[pi] == '*') pi++;
return pi == pl;
}
}

思路 1

另一种思路就是动态规划了,我们定义 dp[i][j] 的真假来表示 s[0..i) 是否匹配 p[0..j),其状态转移方程如下所示:

  • 如果 p[j - 1] != '*'P[i][j] = P[i - 1][j - 1] && (s[i - 1] == p[j - 1] || p[j - 1] == '?');

  • 如果 p[j - 1] == '*'P[i][j] = P[i][j - 1] || P[i - 1][j]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public boolean isMatch(String s, String p) {
if (p.length() == 0) return s.length() == 0;
int sl = s.length(), pl = p.length();
boolean[][] dp = new boolean[sl + 1][pl + 1];
char[] sc = s.toCharArray(), pc = p.toCharArray();
dp[0][0] = true;
for (int i = 1; i <= pl; ++i) {
if (pc[i - 1] == '*') dp[0][i] = dp[0][i - 1];
}
for (int i = 1; i <= sl; ++i) {
for (int j = 1; j <= pl; ++j) {
if (pc[j - 1] != '*') {
dp[i][j] = dp[i - 1][j - 1] && (sc[i - 1] == pc[j - 1] || pc[j - 1] == '?');
} else {
dp[i][j] = dp[i][j - 1] || dp[i - 1][j];
}
}
}
return dp[sl][pl];
}
}

049 Group Anagrams

Description

Given an array of strings, group anagrams together.

For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"],

Return:

1
2
3
4
5
[
["ate", "eat","tea"],
["nat","tan"],
["bat"]
]

Note: All inputs will be in lower-case.

Tags: Hash Table, String

思路

题意是给你一组字符串,让你把其中同位异构字符串分组,同位异构字符串就是组成字符串的字符都相同,但是字符放的位置可以不同。既然要分组,那么关键就是如何确定他们是同位异构字符串呢,想到的自然就是对其排序,排序之后他们就都是同一个字符串了,就可以归为一类了,代码如下所示。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
if (strs == null || strs.length == 0) return Collections.emptyList();
List<List<String>> list = new ArrayList<>();
Map<String, Integer> hash = new HashMap<>();
int i = 0;
for (String str : strs) {
char[] c = str.toCharArray();
Arrays.sort(c);
String sortStr = String.valueOf(c);
if (!hash.containsKey(sortStr)) {
hash.put(sortStr, i++);
List<String> sub = new ArrayList<>();
sub.add(str);
list.add(sub);
} else {
list.get(hash.get(sortStr)).add(str);
}
}
return list;
}
}

050 Pow(x, n)

Description

Implement pow(x, n).

Example 1:

1
2
Input: 2.00000, 10
Output: 1024.00000

Example 2:

1
2
Input: 2.10000, 3
Output: 9.26100

Tags: Math, Binary Search

思路

题意是让你计算 x^n,如果直接计算肯定会超时,那么我们可以想到可以使用二分法来降低时间复杂度。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public double myPow(double x, int n) {
if (n < 0) return helper(1 / x, -n);
return helper(x, n);
}
private double helper(double x, int n) {
if (n == 0) return 1;
if (n == 1) return x;
double d = helper(x, n >>> 1);
if (n % 2 == 0) return d * d;
return d * d * x;
}
}

053 Maximum Subarray

Description

Find the contiguous subarray within an array (containing at least one number) which has the largest sum.

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.

More practice:

If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

Tags: Array, Divide and Conquer, Dynamic Programming

思路 0

题意是求数组中子数组的最大和,这种最优问题一般第一时间想到的就是动态规划,我们可以这样想,当部分序列和大于零的话就一直加下一个元素即可,并和当前最大值进行比较,如果出现部分序列小于零的情况,那肯定就是从当前元素算起。其转移方程就是 dp[i] = nums[i] + (dp[i - 1] > 0 ? dp[i - 1] : 0);,由于我们不需要保留 dp 状态,故可以优化空间复杂度为 1,即 dp = nums[i] + (dp > 0 ? dp : 0);

1
2
3
4
5
6
7
8
9
10
class Solution {
public int maxSubArray(int[] nums) {
int len = nums.length, dp = nums[0], max = dp;
for (int i = 1; i < len; ++i) {
dp = nums[i] + (dp > 0 ? dp : 0);
if (dp > max) max = dp;
}
return max;
}
}

思路 1

题目也给了我们另一种思路,就是分治,所谓分治就是把问题分割成更小的,最后再合并即可,我们把 nums 一分为二先,那么就有两种情况,一种最大序列包括中间的值,一种就是不包括,也就是在左边或者右边;当最大序列在中间的时候那我们就把它两侧的最大和算出即可;当在两侧的话就继续分治即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public int maxSubArray(int[] nums) {
return helper(nums, 0, nums.length - 1);
}
private int helper(int[] nums, int left, int right) {
if (left >= right) return nums[left];
int mid = (left + right) >> 1;
int leftAns = helper(nums, left, mid);
int rightAns = helper(nums, mid + 1, right);
int leftMax = nums[mid], rightMax = nums[mid + 1];
int temp = 0;
for (int i = mid; i >= left; --i) {
temp += nums[i];
if (temp > leftMax) leftMax = temp;
}
temp = 0;
for (int i = mid + 1; i <= right; ++i) {
temp += nums[i];
if (temp > rightMax) rightMax = temp;
}
return Math.max(Math.max(leftAns, rightAns), leftMax + rightMax);
}
}

056 Merge Intervals

Description

Given a collection of intervals, merge all overlapping intervals.

For example,

Given [1,3],[2,6],[8,10],[15,18],

return [1,6],[8,10],[15,18].

Tags: Array, Sort

思路

题意是给你一组区间,让你把区间合并成没有交集的一组区间。我们可以把区间按 start 进行排序,然后遍历排序后的区间,如果当前的 start 小于前者的 end,那么说明这两个存在交集,我们取两者中较大的 end 即可;否则的话直接插入到结果序列中即可。

1
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
/**
* Definition for an interval.
* public class Interval {
* int start;
* int end;
* Interval() { start = 0; end = 0; }
* Interval(int s, int e) { start = s; end = e; }
* }
*/
class Solution {
public List<Interval> merge(List<Interval> intervals) {
if (intervals == null || intervals.size() <= 1) return intervals;
intervals.sort(new Comparator<Interval>() {
@Override
public int compare(Interval o1, Interval o2) {
if (o1.start < o2.start) return -1;
if (o1.start > o2.start) return 1;
return 0;
}
});
List<Interval> ans = new ArrayList<>();
int start = intervals.get(0).start;
int end = intervals.get(0).end;
for (Interval interval : intervals) {
if (interval.start <= end) {
end = Math.max(end, interval.end);
} else {
ans.add(new Interval(start, end));
start = interval.start;
end = interval.end;
}
}
ans.add(new Interval(start, end));
return ans;
}
}

057 Insert Interval

Description

Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).

You may assume that the intervals were initially sorted according to their start times.

Example 1:

Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9].

Example 2:

Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16].

This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10].

Tags: Array, Sort

思路

题意是给你一组有序区间,和一个待插入区间,让你待插入区间插入到前面的区间中,我们分三步走:

  1. 首先把有序区间中小于待插入区间的部分加入到结果中;

  2. 其次是插入待插入区间,如果有交集的话取两者交集的端点值;

  3. 最后把有序区间中大于待插入区间的部分加入到结果中;

1
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
/**
* Definition for an interval.
* public class Interval {
* int start;
* int end;
* Interval() { start = 0; end = 0; }
* Interval(int s, int e) { start = s; end = e; }
* }
*/
class Solution {
public List<Interval> insert(List<Interval> intervals, Interval newInterval) {
if (intervals.isEmpty()) return Collections.singletonList(newInterval);
List<Interval> ans = new ArrayList<>();
int i = 0, len = intervals.size();
for (; i < len; ++i) {
Interval interval = intervals.get(i);
if (interval.end < newInterval.start) ans.add(interval);
else break;
}
for (; i < len; ++i) {
Interval interval = intervals.get(i);
if (interval.start <= newInterval.end) {
newInterval.start = Math.min(newInterval.start, interval.start);
newInterval.end = Math.max(newInterval.end, interval.end);
} else break;
}
ans.add(newInterval);
for (; i < len; ++i) {
ans.add(intervals.get(i));
}
return ans;
}
}

058 Length of Last Word

Description

Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.

If the last word does not exist, return 0.

Note: A word is defined as a character sequence consists of non-space characters only.

Example:

1
2
Input: "Hello World"
Output: 5

Tags: String

思路

题意是让你从一个只包含大小字母和空格字符的字符串中得到最后一个单词的长度,很简单,我们倒序遍历,先得到最后一个非空格字符的索引,然后再得到它前面的空格字符索引,两者相减即可。当然,我们使用 API 来完成这件事更加方便,只需一行代码 return s.trim().length() - s.trim().lastIndexOf(" ") - 1;,但我相信作者出这道题的目的肯定不是考你 API 的使用,所以我们还是用自己的思路来实现。

1
2
3
4
5
6
7
8
9
class Solution {
public int lengthOfLastWord(String s) {
int p = s.length() - 1;
while (p >= 0 && s.charAt(p) == ' ') p--;
int end = p;
while (p >= 0 && s.charAt(p) != ' ') p--;
return end - p;
}
}

066 Plus One

Description

Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.

You may assume the integer do not contain any leading zero, except the number 0 itself.

The digits are stored such that the most significant digit is at the head of the list.

Tags: Array, Math

思路

题意是给你一个数字数组,高位在前,并且首位不为 0 除非这个数组就是 [0],让你给该数组低位加一求其结果,那么我们就模拟小学数学那样进位去算即可,如果一直进位到首位,这种情况也就是都是由 9 组成的数组,此时我们只要 new 出一个多一个长度的数组即可,并把第 0 个元素赋 1 即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public int[] plusOne(int[] digits) {
int p = digits.length - 1;
if (digits[p] < 9) {
digits[p] = ++digits[p];
} else {
do {
digits[p--] = 0;
} while (p >= 0 && digits[p] == 9);
if (digits[0] != 0) {
++digits[p];
} else {
digits = new int[digits.length + 1];
digits[0] = 1;
}
}
return digits;
}
}

067 Add Binary

Description

Given two binary strings, return their sum (also a binary string).

For example,

a = "11"

b = "1"

Return "100".

Tags: Math, String

思路

题意是给你两个二进制串,求其和的二进制串。我们就按照小学算数那么来做,用 carry 表示进位,从后往前算,依次往前,每算出一位就插入到最前面即可,直到把两个二进制串都遍历完即可。

1
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
class Solution {
public String addBinary(String a, String b) {
StringBuilder sb = new StringBuilder();
int carry = 0, p1 = a.length() - 1, p2 = b.length() - 1;
while (p1 >= 0 && p2 >= 0) {
carry += p1 >= 0 ? a.charAt(p1--) - '0' : 0;
carry += p2 >= 0 ? b.charAt(p2--) - '0' : 0;
sb.insert(0, (char) (carry % 2 + '0'));
carry >>= 1;
}
while (p1 >= 0) {
carry += p1 >= 0 ? a.charAt(p1--) - '0' : 0;
sb.insert(0, (char) (carry % 2 + '0'));
carry >>= 1;
}
while (p2 >= 0) {
carry += p2 >= 0 ? b.charAt(p2--) - '0' : 0;
sb.insert(0, (char) (carry % 2 + '0'));
carry >>= 1;
}
if (carry == 1) {
sb.insert(0, '1');
}
return sb.toString();
}
}

068 Text Justification

Description

Given an array of words and a length L, format the text such that each line has exactly L characters and is fully (left and right) justified.

You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' ' when necessary so that each line has exactly L characters.

Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line do not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.

For the last line of text, it should be left justified and no extra space is inserted between words.

For example,

words: ["This", "is", "an", "example", "of", "text", "justification."]

L: 16.

Return the formatted lines as:

1
2
3
4
5
[
"This is an",
"example of text",
"justification. "
]

Note: Each word is guaranteed not to exceed L in length.

Corner Cases:

  • A line other than the last line might contain only one word. What should you do in this case?

    In this case, that line should be left-justified.

Tags: String

思路

题意是给你一组单词和最大行宽,让你对齐他们,对齐的规则就是尽可能一行可以放下足够多的单词,如果最后有多余的空格,那就把空格均匀地插入到单词之间,如果不能平分的话,那就从左开始依次多插一个空格,最后一行单词之间就正常地一个空格即可,如果凑不到最大行宽,那就在末尾补充空格即可,描述地比较差,不懂的话其实看看 demo 也就懂了哈。题还是比较坑的,毕竟踩的比赞的人多,我也是靠模拟老老实实做出来的,求出可以最多插入空格数,然后用它除以可以插入的槽数获取每个单词之间的空格,它两取余的话就是最面需要多插入一个空格的个数,最后一行的话就单独处理即可。

1
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
class Solution {
public List<String> fullJustify(String[] words, int maxWidth) {
int len = words.length;
List<String> ans = new ArrayList<>();
StringBuilder spaces = new StringBuilder();
for (int i = 0; i < maxWidth; ++i) {
spaces.append(" ");
}
int curLen = -1, start = 0;
for (int i = 0; i < len; ++i) {
if (curLen + words[i].length() + 1 <= maxWidth) {
curLen += words[i].length() + 1;
} else {
StringBuilder sub = new StringBuilder(words[start]);
int rest = maxWidth - curLen;
int l = i - start - 1;
if (l <= 0) {
sub.append(spaces.substring(0, rest));
} else {
int m = rest / l + 1;
int mod = rest % l;
for (int j = start + 1; j < i; ++j) {
if (mod-- > 0) {
sub.append(spaces.substring(0, m + 1)).append(words[j]);
} else {
sub.append(spaces.substring(0, m)).append(words[j]);
}
}
}
ans.add(sub.toString());
start = i;
curLen = words[i].length();
}
}
StringBuilder sub = new StringBuilder(words[start]);
for (int i = start + 1; i < len; ++i) {
sub.append(" ").append(words[i]);
}
ans.add(sub + spaces.substring(0, maxWidth - sub.length()));
return ans;
}
}

069 Sqrt(x)

Description

Implement int sqrt(int x).

Compute and return the square root of x.

x is guaranteed to be a non-negative integer.

Example 1:

1
2
Input: 4
Output: 2

Example 2:

1
2
3
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.

Tags: Binary Search, Math

思路

题意是求平方根,参考 牛顿迭代法求平方根,然后再参考维基百科的 Integer square root 即可。

1
2
3
4
5
6
7
8
9
class Solution {
public int mySqrt(int x) {
long n = x;
while (n * n > x) {
n = (n + x / n) >> 1;
}
return (int) n;
}
}

070 Climbing Stairs

Description

You are climbing a stair case. It takes n steps to reach to the top.

Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

Note: Given n will be a positive integer.

Example 1:

1
2
3
4
5
6
Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps

Example 2:

1
2
3
4
5
6
7
Input: 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step

Tags: Dynamic Programming

思路

题意是爬楼梯,每次你只能爬一步或者两步,问到顶层共有多少种方案。我们假设到顶层共有 f(n) 种,那么 f(n) = f(n - 1) + f(n - 2) 肯定是成立的,意思就是我们迈向顶层的最后一步是在倒数第一级台阶或者在倒数第二级台阶。算法我对空间复杂度进行了优化,因为在迭代过程中只需要两个变量即可。

1
2
3
4
5
6
7
8
9
10
class Solution {
public int climbStairs(int n) {
int a = 1, b = 1;
while (--n > 0) {
b += a;
a = b - a;
}
return b;
}
}

083Remove Duplicates from Sorted List

Description

Given a sorted linked list, delete all duplicates such that each element appear only once.

For example,

Given 1->1->2, return 1->2.

Given 1->1->2->3->3, return 1->2->3.

Tags: Linked List

思路

题意是删除链表中重复的元素,很简单,我们只需要遍历一遍链表,遇到链表中相邻元素相同时,把当前指针指向下下个元素即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if (head == null || head.next == null) return head;
ListNode curr = head;
while (curr.next != null) {
if (curr.next.val == curr.val) {
curr.next = curr.next.next;
} else {
curr = curr.next;
}
}
return head;
}
}

088 Merge Sorted Array

Description

Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

Note:

You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively.

Tags: Array, Two Pointers

思路

题意是给两个已排序的数组 nums1nums2,合并 nums2nums1 中,两数组元素个数分别为 mn,而且 nums1 数组的长度足够容纳 m + n 个元素,如果我们按顺序排下去,那肯定要开辟一个新数组来保存元素,如果我们选择逆序,这样利用 nums1 自身空间足矣,不会出现覆盖的情况,依次把大的元素插入到 nums1 的末尾,确保 nums2 中的元素全部插入到 nums1 即可。

1
2
3
4
5
6
7
8
9
class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
int p = m-- + n-- - 1;
while (m >= 0 && n >= 0)
nums1[p--] = nums1[m] > nums2[n] ? nums1[m--] : nums2[n--];
while (n >= 0)
nums1[p--] = nums2[n--];
}
}

100 Same Tree

Description

Given two binary trees, write a function to check if they are the same or not.

Two binary trees are considered the same if they are structurally identical and the nodes have the same value.

Example 1:

1
2
3
4
5
6
7
Input: 1 1
/ \ / \
2 3 2 3
[1,2,3], [1,2,3]
Output: true

Example 2:

1
2
3
4
5
6
7
Input: 1 1
/ \
2 2
[1,2], [1,null,2]
Output: false

Example 3:

1
2
3
4
5
6
7
Input: 1 1
/ \ / \
2 1 1 2
[1,2,1], [1,1,2]
Output: false

Tags: Tree, Depth-first Search

思路

题意是比较两棵二叉树是否相同,那么我们就深搜比较各个节点即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if (p == null && q == null) return true;
if (p == null || q == null) return false;
if (p.val == q.val) {
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
return false;
}
}

101 Symmetric Tree

Description

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree [1,2,2,3,4,4,3] is symmetric:

1
2
3
4
5
1
/ \
2 2
/ \ / \
3 4 4 3

But the following [1,2,2,null,3,null,3] is not:

1
2
3
4
5
1
/ \
2 2
\ \
3 3

Note:

Bonus points if you could solve it both recursively and iteratively.

Tags: Tree, Depth-first Search, Breadth-first Search

思路 0

题意是判断一棵二叉树是否左右对称,首先想到的是深搜,比较根结点的左右两棵子树是否对称,如果左右子树的值相同,那么再分别对左子树的左节点和右子树的右节点,左子树的右节点和右子树的左节点做比较即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isSymmetric(TreeNode root) {
return root == null || helper(root.left, root.right);
}
public boolean helper(TreeNode left, TreeNode right) {
if (left == null || right == null) return left == right;
if (left.val != right.val) return false;
return helper(left.left, right.right) && helper(left.right, right.left);
}
}

思路 1

第二种思路就是宽搜了,宽搜肯定要用到队列,Java 中可用 LinkedList 替代,也是要做到左子树的左节点和右子树的右节点,左子树的右节点和右子树的左节点做比较即可。

1
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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isSymmetric(TreeNode root) {
if (root == null) return true;
LinkedList<TreeNode> q = new LinkedList<>();
q.add(root.left);
q.add(root.right);
TreeNode left, right;
while (q.size() > 1) {
left = q.pop();
right = q.pop();
if (left == null && right == null) continue;
if (left == null || right == null) return false;
if (left.val != right.val) return false;
q.add(left.left);
q.add(right.right);
q.add(left.right);
q.add(right.left);
}
return true;
}
}

104 Maximum Depth of Binary Tree

Description

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Tags: Tree, Depth-first Search

思路

题意是找到二叉树的最大深度,很明显,深搜即可,每深入一次节点加一即可,然后取左右子树的最大深度。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int maxDepth(TreeNode root) {
if (root == null) return 0;
return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
}
}

107 Binary Tree Level Order Traversal II

Description

Given a binary tree, return the bottom-up level order traversal of its nodes’ values. (ie, from left to right, level by level from leaf to root).

For example:

Given binary tree [3,9,20,null,null,15,7],

1
2
3
4
5
3
/ \
9 20
/ \
15 7

return its bottom-up level order traversal as:

1
2
3
4
5
[
[15,7],
[9,20],
[3]
]

Tags: Tree, Breadth-first Search

思路 0

题意是从下往上按层遍历二叉树,每一层是从左到右,按层遍历,很明显,宽搜第一时间符合,因为是从下往上,所以插入的时候每次插到链表头即可。

1
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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
if (root == null) return Collections.emptyList();
List<List<Integer>> list = new LinkedList<>();
LinkedList<TreeNode> q = new LinkedList<>();
q.add(root);
while(!q.isEmpty()) {
int size = q.size();
List<Integer> sub = new LinkedList();
for(int i = 0; i < size; ++i) {
TreeNode node = q.remove();
sub.add(node.val);
if (node.left != null) q.add(node.left);
if (node.right != null) q.add(node.right);
}
list.add(0, sub);
}
return list;
}
}

思路 1

另一种思路就是深搜,深搜的时候同时记录深度,然后在相应的层插入节点值即可。

1
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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
List<List<Integer>> list = new LinkedList<>();
helper(list, root, 0);
return list;
}
private void helper(List<List<Integer>> list, TreeNode root, int level) {
if (root == null) return;
if (level >= list.size()) {
list.add(0, new LinkedList<>());
}
helper(list, root.left, level + 1);
helper(list, root.right, level + 1);
list.get(list.size() - level - 1).add(root.val);
}
}

108 Convert Sorted Array to Binary Search Tree

Description

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

Example:

1
2
3
4
5
6
7
8
9
Given the sorted array: [-10,-3,0,5,9],
One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:
0
/ \
-3 9
/ /
-10 5

Tags: Tree, Depth-first Search

思路

题意是把一个有序数组转化为一棵二叉搜索树,二叉搜索树具有以下性质:

  1. 若任意节点的左子树不空,则左子树上所有节点的值均小于它的根节点的值;

  2. 若任意节点的右子树不空,则右子树上所有节点的值均大于它的根节点的值;

  3. 任意节点的左、右子树也分别为二叉查找树;

  4. 没有键值相等的节点。

所以我们可以用递归来构建一棵二叉搜索树,每次把数组分为两半,把数组中间的值作为其父节点,然后把数组的左右两部分继续构造其左右子树。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
if (nums == null || nums.length == 0) return null;
return helper(nums, 0, nums.length - 1);
}
private TreeNode helper(int[] nums, int left, int right) {
if (left > right) return null;
int mid = (left + right) >>> 1;
TreeNode node = new TreeNode(nums[mid]);
node.left = helper(nums, left, mid - 1);
node.right = helper(nums, mid + 1, right);
return node;
}
}

110 Balanced Binary Tree

Description

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

Tags: Tree, Depth-first Search

思路

题意是判断一棵二叉树是否是高度平衡的,所谓二叉树高度平衡指的是二叉树的每个节点的两棵子树的高度差都不超过 1,那么我们只需计算左右子树的高度,判断其高度差是否不超过 1 即可,如果超过 1,就代表其不是高度平衡的,立即返回不是即可,我这里用返回 -1 代表不是。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isBalanced(TreeNode root) {
return helper(root) != -1;
}
private int helper(TreeNode node) {
if (node == null) return 0;
int l = helper(node.left);
if (l == -1) return -1;
int r = helper(node.right);
if (r == -1) return -1;
if (Math.abs(l - r) > 1) return -1;
return 1 + Math.max(l, r);
}
}

111 Minimum Depth of Binary Tree

Description

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

Tags: Tree, Depth-first Search, Breadth-first Search

思路 0

题意是查找二叉树的最小深度,也就是找到从根结点到叶子节点的最小深度,最容易想到的当然是深搜,如果节点的左右深度都不是 0 的话,说明该节点含有左右子树,所以它的最小高度就是 1 加上其左右子树高度较小者,否则如果左子树为空或者右子树为空或者两者都为空,那么就是 1 加上非空子树高度。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int minDepth(TreeNode root) {
if (root == null) return 0;
int l = minDepth(root.left);
int r = minDepth(root.right);
if (l != 0 && r != 0) return 1 + Math.min(l, r);
return l + r + 1;
}
}

思路 1

第二种思路就是利用宽搜了,搜索到该层有叶子节点,那就返回该层宽度即可。

1
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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int minDepth(TreeNode root) {
if (root == null) return 0;
LinkedList<TreeNode> q = new LinkedList<>();
q.add(root);
int ans = 1;
while (!q.isEmpty()) {
int size = q.size();
for (int i = 0; i < size; ++i) {
TreeNode node = q.remove();
if (node.left == null && node.right == null) {
return ans;
}
if (node.left != null) q.add(node.left);
if (node.right != null) q.add(node.right);
}
++ans;
}
return 520;
}
}

112 Path Sum

Description

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

For example:

Given the below binary tree and sum = 22,

1
2
3
4
5
6
7
5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1

return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

Tags: Tree, Depth-first Search

思路

题意是查找二叉树中是否存在从根结点到叶子的路径和为某一值,利用深搜在遇到叶子节点时判断是否满足即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
if (root == null) return false;
if (root.left == null && root.right == null) return sum == root.val;
return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
}
}

118 Pascal’s Triangle

Description

Given numRows, generate the first numRows of Pascal’s triangle.

For example, given numRows = 5,

Return

1
2
3
4
5
6
7
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]

Tags: Array

思路

题意是给出行数,输出帕斯卡尔三角形,很简单的模拟,就不多说了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public List<List<Integer>> generate(int numRows) {
if (numRows == 0) return Collections.emptyList();
List<List<Integer>> list = new ArrayList<>();
for (int i = 0; i < numRows; ++i) {
List<Integer> sub = new ArrayList<>();
for (int j = 0; j <= i; ++j) {
if (j == 0 || j == i) {
sub.add(1);
} else {
List<Integer> upSub = list.get(i - 1);
sub.add(upSub.get(j - 1) + upSub.get(j));
}
}
list.add(sub);
}
return list;
}
}

119 Pascal’s Triangle II

Description

Given an index k, return the kth row of the Pascal’s triangle.

For example, given k = 3,

Return [1,3,3,1].

Note:

Could you optimize your algorithm to use only O(k) extra space?

Tags: Array

思路

题意是指定输出帕斯卡尔三角形的某一行,模拟即可,优化后的代码如下所示。

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public List<Integer> getRow(int rowIndex) {
List<Integer> res = new ArrayList<>();
for (int i = 0; i <= rowIndex; ++i) {
res.add(1);
for (int j = i - 1; j > 0; --j) {
res.set(j, res.get(j - 1) + res.get(j));
}
}
return res;
}
}

121 Best Time to Buy and Sell Stock

Description

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Example 1:

1
2
3
4
Input: [7, 1, 5, 3, 6, 4]
Output: 5
max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)

Example 2:

1
2
3
4
Input: [7, 6, 4, 3, 1]
Output: 0
In this case, no transaction is done, i.e. max profit = 0.

Tags: Array, Dynamic Programmin

思路

题意是给出一个数组代表每天的股票金额,让你在最多买卖一次的情况下算出最大的收益额,最简单的就是模拟即可,每次记录当前值减去最小值的差值,与上一次的进行比较然后更新最大值即可。

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public int maxProfit(int[] prices) {
int max = 0, minPrice = Integer.MAX_VALUE;
for (int i = 0; i < prices.length; ++i) {
if (prices[i] < minPrice) minPrice = prices[i];
int delta = prices[i] - minPrice;
if (delta > max) max = delta;
}
return max;
}
}

122 Best Time to Buy and Sell Stock II

Description

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

Tags: Array, Greedy

思路

题意是给出一个数组代表每天的股票金额,在每天只能买或卖的情况下求出收益最高值,这…,这也太简单了吧,把所有相邻递增的值都加起来即可。

1
2
3
4
5
6
7
8
9
class Solution {
public int maxProfit(int[] prices) {
int max = 0;
for (int i = 1; i < prices.length; ++i) {
if (prices[i] > prices[i - 1]) max += prices[i] - prices[i - 1];
}
return max;
}
}

543 Diameter of Binary Tree

Description

Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.

Example:

Given a binary tree

1
2
3
4
5
1
/ \
2 3
/ \
4 5

Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].

Note: The length of path between two nodes is represented by the number of edges between them.

Tags: Tree

思路

题意是让你算出二叉树中最远的两个节点的距离,分别计算左右子树的最大高度,然后不断迭代出其和的最大值就是最终结果。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int max = 0;
public int diameterOfBinaryTree(TreeNode root) {
helper(root);
return max;
}
private int helper(TreeNode root) {
if (root == null) return 0;
int l = helper(root.left);
int r = helper(root.right);
if (l + r > max) max = l + r;
return Math.max(l, r) + 1;
}
}

554 Brick Wall

Description

There is a brick wall in front of you. The wall is rectangular and has several rows of bricks. The bricks have the same height but different width. You want to draw a vertical line from the top to the bottom and cross the least bricks.

The brick wall is represented by a list of rows. Each row is a list of integers representing the width of each brick in this row from left to right.

If your line go through the edge of a brick, then the brick is not considered as crossed. You need to find out how to draw the line to cross the least bricks and return the number of crossed bricks.

You cannot draw a line just along one of the two vertical edges of the wall, in which case the line will obviously cross no bricks.

Example:

1
2
3
4
5
6
7
8
Input:
[[1,2,2,1],
[3,1,2],
[1,3,2],
[2,4],
[3,1,2],
[1,3,1,1]]
Output: 2

Explanation:
img

Note:

  1. The width sum of bricks in different rows are the same and won’t exceed INT_MAX.

  2. The number of bricks in each row is in range [1,10,000]. The height of wall is in range [1,10,000]. Total number of bricks of the wall won’t exceed 20,000.

Tags: Hash Table

思路

题意根据图示已经描述得很清楚了,就是在从底部到顶部,求最少交叉的数量,我们可以把每堵墙可以穿过的地方保存到哈希表中,每次遇到哈希表中的值加一,代表就是这条路不用交叉的数量,最终我们可以算出不用交叉的最大值,让总墙数减去其值就是最少交叉的数量。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public int leastBricks(List<List<Integer>> wall) {
Map<Integer, Integer> map = new HashMap<>();
int width = 0, max = 0;
for (List<Integer> sub : wall) {
int p = 0;
for (int i = 0, len = sub.size() - 1; i < len; ++i) {
p += sub.get(i);
Integer v = map.get(p);
map.put(p, (v == null ? 0 : v) + 1);
}
}
for (Integer integer : map.values()) {
if (integer > max) max = integer;
}
return wall.size() - max;
}
}

标签云