0%

algorithm-dc

简单

将有序数组转换为二叉搜索树

题目描述

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
给你一个整数数组 nums ,其中元素已经按 升序 排列,请你将其转换为一棵 
平衡
二叉搜索树。



示例 1:

输入:nums = [-10,-3,0,5,9]
输出:[0,-3,9,-10,null,5]
解释:[0,-10,5,null,-3,null,9] 也将被视为正确答案:

示例 2:

输入:nums = [1,3]
输出:[3,1]
解释:[1,null,3] 和 [3,1] 都是高度平衡二叉搜索树。


提示:

1 <= nums.length <= 104
-104 <= nums[i] <= 104
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
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
public class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
return genBSTTree(nums, 0, nums.length - 1);
}

public TreeNode genBSTTree(int[] nums, int L, int R) {
if (L > R) {
return null;
}

int M = (L + R) / 2;
TreeNode node = new TreeNode(nums[M]);
node.left = genBSTTree(nums, L, M - 1);
node.right = genBSTTree(nums, M + 1, R);

return node;
}

static class TreeNode {
int val;
TreeNode left;
TreeNode right;

TreeNode() {
}

TreeNode(int val) {
this.val = val;
}

TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}

public static TreeNode genTree(Integer[] array) {
if (array.length == 0) {
return null;
}

java.util.Queue<TreeNode> queue = new java.util.LinkedList<>();
TreeNode root = new TreeNode(array[0]);
queue.offer(root);

Integer v = null;
int i = 1;
while (i < array.length) {
TreeNode node = queue.poll();

TreeNode left = i < array.length && (v = array[i++]) != null ? new TreeNode(v) : null;
TreeNode right = i < array.length && (v = array[i++]) != null ? new TreeNode(v) : null;

// 数组中不包含空节点的子节点的写法(不标准的完全二叉树含空节点的层次遍历)
node.left = left;
node.right = right;
if (left != null) {
queue.offer(left);
}
if (right != null) {
queue.offer(right);
}

// 数组中包含空节点的子节点的写法(标准的完全二叉树含空节点的层次遍历)
// if (node != null) {
// node.left = left;
// node.right = right;
// }
// queue.offer(left);
// queue.offer(right);
}

return root;
}

public static Integer[] toArray(TreeNode root) {
if (root == null) {
return new Integer[0];
}

java.util.LinkedList<Integer> list = new java.util.LinkedList<>();

java.util.Queue<TreeNode> queue = new java.util.LinkedList<>();
queue.offer(root);

while (!queue.isEmpty()) {
boolean hasValidNode = false;

int size = queue.size();
for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();

if (node != null) {
list.add(node.val);

queue.offer(node.left);
queue.offer(node.right);

if (!hasValidNode) {
hasValidNode = node.left != null || node.right != null;
}
} else {
list.add(null);
}
}

if (!hasValidNode) {
// while (!queue.isEmpty()) {
// queue.poll();
// }

break;
}
}

while (!list.isEmpty() && list.get(list.size() - 1) == null) {
list.remove(list.size() - 1);
}

return list.toArray(new Integer[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
给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表 。



示例 1:


输入:head = [4,2,1,3]
输出:[1,2,3,4]
示例 2:


输入:head = [-1,5,3,4,0]
输出:[-1,0,3,4,5]
示例 3:

输入:head = []
输出:[]


提示:

链表中节点的数目在范围 [0, 5 * 104] 内
-105 <= Node.val <= 105


进阶:你可以在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序吗?

题目解答

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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
public class Solution {
public ListNode sortList(ListNode head) {
return mergeSort(head);
}

public ListNode mergeSort(ListNode head) {
if (head == null) {
return null;
}

if (head.next == null) {
return head;
}

ListNode l1 = head;
ListNode l2 = head.next;
l1.next = null;

ListNode p = mergeSort(l1);
ListNode q = mergeSort(l2);

ListNode h = null;
ListNode t = null;

while (p != null && q != null) {
while (p != null && q != null && p.val <= q.val) {
if (t == null) {
t = p;
h = t;
} else {
t.next = p;
t = p;
}

p = p.next;
}

while (p != null && q != null && q.val <= p.val) {
if (t == null) {
t = q;
h = t;
} else {
t.next = q;
t = q;
}

q = q.next;
}
}

while (p != null) {
t.next = p;
t = p;

p = p.next;
}
while (q != null) {
t.next = q;
t = q;

q = q.next;
}

return h;
}

static class ListNode {
int val;
ListNode next;

ListNode(int x) {
val = x;
next = null;
}

public static ListNode genLinkedList(int[] nums, boolean withHead, int loopPos) {
if (nums.length == 0) {
return null;
}

int val = withHead ? Integer.MIN_VALUE : nums[0];
ListNode head = new ListNode(val);

ListNode loop = withHead ? null : loopPos == 0 ? head : null;

int b = withHead ? 0 : 1;
ListNode p = head;
for (int i = b; i < nums.length; i++) {
p.next = new ListNode(nums[i]);
p = p.next;

if (loopPos == i) {
loop = p;
}
}

if (loop != null) {
p.next = loop;
}

return head;
}

public static ListNode genLinkedListWithHeadNode(int[] nums) {
return genLinkedList(nums, true, -1);
}

public static ListNode genLinkedListWithoutHeadNode(int[] nums) {
return genLinkedList(nums, false, -1);
}

public static ListNode genLoopedLinkedListWithHeadNode(int[] nums, int pos) {
return genLinkedList(nums, true, pos);
}

public static ListNode genLoopedLinkedListWithoutHeadNode(int[] nums, int pos) {
return genLinkedList(nums, false, pos);
}

public static int getCount(ListNode head, boolean withHead) {
ListNode p = withHead ? head.next : head;

int c = 0;
while (p != null) {
c++;
p = p.next;
}

return c;
}

public static int[] toArray(ListNode head, boolean withHead) {
int c = getCount(head, withHead);
int[] nums = new int[c];

ListNode p = withHead ? head.next : head;

int k = 0;
while (p != null) {
nums[k] = p.val;

k++;
p = p.next;
}

return nums;
}

public static int[] toArrayWithHeadNode(ListNode head) {
return toArray(head, true);
}

public static int[] toArrayWithoutHeadNode(ListNode head) {
return toArray(head, false);
}
}
}

class TestMain {

public static void main(String[] args) {
TestUtils.runTestCases(TestCase.class);
}

public static class TestCase {

public static boolean testCase1() {
int[] nums = { 4, 2, 1, 3 };

Solution.ListNode head = Solution.ListNode.genLinkedListWithoutHeadNode(nums);

head = new Solution().sortList(head);
int[] result = Solution.ListNode.toArrayWithoutHeadNode(head);
int[] expect = { 1, 2, 3, 4 };

return TestUtils.check(result, expect);
}

public static boolean testCase2() {
int[] nums = { -1, 5, 3, 4, 0 };

Solution.ListNode head = Solution.ListNode.genLinkedListWithoutHeadNode(nums);

head = new Solution().sortList(head);
int[] result = Solution.ListNode.toArrayWithoutHeadNode(head);
int[] expect = { -1, 0, 3, 4, 5 };

return TestUtils.check(result, expect);
}

public static boolean testCase3() {
int[] nums = {};

Solution.ListNode head = Solution.ListNode.genLinkedListWithoutHeadNode(nums);

head = new Solution().sortList(head);
int[] result = Solution.ListNode.toArrayWithoutHeadNode(head);
int[] expect = {};

return TestUtils.check(result, expect);
}
}

public static class TestUtils {

public static boolean check(Object result, Object expect) {
result = normalizeObject(result);
expect = normalizeObject(expect);
boolean ok = java.util.Objects.deepEquals(result, expect);
printCheck(toString(result), toString(expect), ok);
return ok;
}

public static boolean check(Object result, String expect) {
boolean ok = java.util.Objects.equals(normalizeString(toString(result)),
normalizeString(toString(expect)));
printCheck(normalizeString(toString(result)), normalizeString(toString(expect)), ok);
return ok;
}

private static Object normalizeObject(Object o) {
if (o instanceof java.util.List) {
java.util.List<?> list = (java.util.List<?>) o;
if (list != null && !list.isEmpty() && list.get(0) instanceof java.util.List) {
o = toArrays(list);
} else {
o = toArray(list);
}
}

return o;
}

private static String toString(Object o) {
if (o instanceof Object[]) {
return java.util.Arrays.deepToString((Object[]) o);
} else if (o instanceof int[]) {
return java.util.Arrays.toString((int[]) o);
} else if (o instanceof double[]) {
return java.util.Arrays.toString((double[]) o);
} else if (o instanceof char[]) {
return java.util.Arrays.toString((char[]) o);
} else {
return java.util.Objects.toString(o);
}
}

private static String normalizeString(String s) {
boolean isArray = (s.startsWith("{") && s.endsWith("}")) || (s.startsWith("[") && s.endsWith("]"));
if (isArray) {
s = s.replace(" ", "")
.replace("'", "")
.replace("\"", "")
.replace("{", "[")
.replace("}", "]");
}

return s;
}

private static void printCheck(String result, String expect, boolean ok) {
// System.out.println();
// System.out.println("--->");

System.out.println("result: " + result);
System.out.println("expect: " + expect);

System.out.println();
if (ok) {
System.out.println("比较结果为: 正确(right)");
} else {
System.out.println("比较结果为: 错误(error)");
}

// System.out.println();
// System.out.println("<---");
}

public static void runTestCases(Class<?> clazz) {
java.lang.reflect.Method[] methods = clazz.getDeclaredMethods();
java.util.Arrays.sort(methods, (o1, o2) -> {
return o1.getName().compareTo(o2.getName());
});
for (java.lang.reflect.Method method : methods) {
if (method.getName().startsWith("test")) {
System.out.println(String.format("--- %s --->", method.getName()));

Object object = null;
try {
object = method.invoke(null);
} catch (Exception e) {
e.printStackTrace();
}

System.out.println(String.format("<--- %s ---", method.getName()));

if (object instanceof Boolean) {
Boolean ok = (Boolean) object;
if (!ok) {
break;
}
} else {
throw new RuntimeException(String.format("测试用例方法%s的返回值需要为布尔类型", method.getName()));
}
}
}
}

public static Object[] toArray(Object o) {
java.util.List<?> list = (java.util.List<?>) o;
if (list == null || list.isEmpty()) {
return new Object[0];
}

return list.toArray();
}

public static Object[][] toArrays(Object o) {
java.util.List<?> list = (java.util.List<?>) o;
if (list == null || list.isEmpty()) {
return new Object[0][0];
}

Object[][] arrays = new Object[list.size()][];
for (int i = 0; i < list.size(); i++) {
arrays[i] = toArray(list.get(i));
}

return arrays;
}

@SuppressWarnings("unchecked")
public static <T> T[] genArray(Class<T> clazz, int length) {
return (T[]) java.lang.reflect.Array.newInstance(clazz, length);
}

@SuppressWarnings("unchecked")
public static <T> T[][] genArrays(Class<T> clazz, int rows, int cols) {
T[] array = genArray(clazz, 0);

T[][] arrays = (T[][]) genArray(array.getClass(), rows);
for (int i = 0; i < arrays.length; i++) {
arrays[i] = genArray(clazz, cols);
}

return arrays;
}

public static <T> T[] toArray(java.util.List<T> list, Class<T> clazz) {
if (list == null || list.isEmpty()) {
return genArray(clazz, 0);
}

T[] array = genArray(clazz, list.size());
for (int i = 0; i < array.length; i++) {
array[i] = list.get(i);
}

return array;
}

public static <T> T[][] toArrays(java.util.List<java.util.List<T>> lists, Class<T> clazz) {
if (lists == null || lists.isEmpty()) {
return genArrays(clazz, 0, 0);
}

T[][] arrays = genArrays(clazz, lists.size(), 0);
for (int i = 0; i < lists.size(); i++) {
arrays[i] = toArray(lists.get(i), clazz);
}

return arrays;
}

public static <T> java.util.List<T> toList(T[] array) {
return java.util.Arrays.asList(array);
}

public static <T> java.util.List<java.util.List<T>> toLists(T[][] arrays) {
java.util.List<java.util.List<T>> lists = new java.util.ArrayList<>();
for (T[] array : arrays) {
lists.add(toList(array));
}

return lists;
}
}
}

建立四叉树

题目描述

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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
给你一个 n * n 矩阵 grid ,矩阵由若干 0 和 1 组成。请你用四叉树表示该矩阵 grid 。

你需要返回能表示矩阵 grid 的 四叉树 的根结点。

四叉树数据结构中,每个内部节点只有四个子节点。此外,每个节点都有两个属性:

val:储存叶子结点所代表的区域的值。1 对应 True,0 对应 False。注意,当 isLeaf 为 False 时,你可以把 True 或者 False 赋值给节点,两种值都会被判题机制 接受 。
isLeaf: 当这个节点是一个叶子结点时为 True,如果它有 4 个子节点则为 False 。
class Node {
public boolean val;
public boolean isLeaf;
public Node topLeft;
public Node topRight;
public Node bottomLeft;
public Node bottomRight;
}
我们可以按以下步骤为二维区域构建四叉树:

如果当前网格的值相同(即,全为 0 或者全为 1),将 isLeaf 设为 True ,将 val 设为网格相应的值,并将四个子节点都设为 Null 然后停止。
如果当前网格的值不同,将 isLeaf 设为 False, 将 val 设为任意值,然后如下图所示,将当前网格划分为四个子网格。
使用适当的子网格递归每个子节点。


如果你想了解更多关于四叉树的内容,可以参考 wiki 。

四叉树格式:

你不需要阅读本节来解决这个问题。只有当你想了解输出格式时才会这样做。输出为使用层序遍历后四叉树的序列化形式,其中 null 表示路径终止符,其下面不存在节点。

它与二叉树的序列化非常相似。唯一的区别是节点以列表形式表示 [isLeaf, val] 。

如果 isLeaf 或者 val 的值为 True ,则表示它在列表 [isLeaf, val] 中的值为 1 ;如果 isLeaf 或者 val 的值为 False ,则表示值为 0 。



示例 1:



输入:grid = [[0,1],[1,0]]
输出:[[0,1],[1,0],[1,1],[1,1],[1,0]]
解释:此示例的解释如下:
请注意,在下面四叉树的图示中,0 表示 false,1 表示 True 。

示例 2:



输入:grid = [[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0]]
输出:[[0,1],[1,1],[0,1],[1,1],[1,0],null,null,null,null,[1,0],[1,0],[1,1],[1,1]]
解释:网格中的所有值都不相同。我们将网格划分为四个子网格。
topLeft,bottomLeft 和 bottomRight 均具有相同的值。
topRight 具有不同的值,因此我们将其再分为 4 个子网格,这样每个子网格都具有相同的值。
解释如下图所示:



提示:

n == grid.length == grid[i].length
n == 2x 其中 0 <= x <= 6

题目解答

1
//

TODO:建立四叉树

困难

合并K个升序链表

题目描述

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
给你一个链表数组,每个链表都已经按升序排列。

请你将所有链表合并到一个升序链表中,返回合并后的链表。



示例 1:

输入:lists = [[1,4,5],[1,3,4],[2,6]]
输出:[1,1,2,3,4,4,5,6]
解释:链表数组如下:
[
1->4->5,
1->3->4,
2->6
]
将它们合并到一个有序链表中得到。
1->1->2->3->4->4->5->6
示例 2:

输入:lists = []
输出:[]
示例 3:

输入:lists = [[]]
输出:[]


提示:

k == lists.length
0 <= k <= 10^4
0 <= lists[i].length <= 500
-10^4 <= lists[i][j] <= 10^4
lists[i] 按 升序 排列
lists[i].length 的总和不超过 10^4

题目解答

1
//

TODO:合并K个升序链表

只想买包辣条