-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
4077 lines (3876 loc) · 126 KB
/
Copy pathSolution.java
File metadata and controls
4077 lines (3876 loc) · 126 KB
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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package leetcode;
import leetcode.entity.Entry;
import leetcode.entity.ListNode;
import leetcode.entity.Node;
import leetcode.entity.TreeNode;
import java.util.*;
class Solution {
int result = 0;
/*
* @description: 1.两数之和,从数组中找出两个数使其和为target
* @param: nums:int数组,target:目标值
* @return: int[]:数组下标
*/
public int[] twoSum(int[] nums, int target) {
//key:值 value:数组下标
HashMap<Integer, Integer> numberIndex = new HashMap();
int[] result = new int[2];
for (int i = 0, l = nums.length; i < l; i++) {
//判断与当前值和为target的值是否存在
int index = numberIndex.getOrDefault(target - nums[i], -1);
if (index != -1) {
result[0] = index;
result[1] = i;
break;
}
numberIndex.put(nums[i], i);
}
return result;
}
/*
* @description: 2.两数相加,将两个链表每个结点相加
* @param: l1,l2:非空链表
* @return: ListNode:相加后的结果链表
*/
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
//记录初始node的地址,用来return
ListNode head = new ListNode(0);
//游标
ListNode cursor = head;
int carry = 0;
while (l1 != null || l2 != null || carry != 0) {
int val1 = 0, val2 = 0;
if (l1 != null) {
val1 = l1.val;
l1 = l1.next;
}
if (l2 != null) {
val2 = l2.val;
l2 = l2.next;
}
int result = val1 + val2 + carry;
carry = result / 10;
cursor.next = new ListNode(result % 10);
cursor = cursor.next;
}
return head.next;
}
/*
* @description: 3.无重复的最长子串
* @param: s:字符串
* @return: 无重复字符最长的字串的长度
*/
public int lengthOfLongestSubstring(String s) {
int maxLength = 0;
Map<Character, Integer> charIndex = new HashMap<>();
for (int i = 0, j = 0, l = s.length(); j < l; j++) {
i = Math.max(charIndex.getOrDefault(s.charAt(j), -1), i);
maxLength = Math.max(maxLength, j - i + 1);
charIndex.put(s.charAt(j), j + 1);
}
return maxLength;
}
/*
* @description: 4.寻找两个正序数组的中位数,时间复杂度O(log(m + n))
* @param: nums1,nums2:有序int数组
* @return: double:中位数
*/
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int length = nums1.length + nums2.length;
//奇数情况,取中间的一个数即可
if ((length & 1) == 1) {
return getTopK(nums1, 0, nums2, 0, length / 2 + 1) / 1.0;
}
//偶数情况,取中间2位数求平均值
return (getTopK(nums1, 0, nums2, 0, length / 2) + getTopK(nums1, 0, nums2, 0, length / 2 + 1)) / 2.0;
}
/*
* @description: 获取两个数组中第k大的数
* @param: num1,num2为 int数组,index1为num1起始下标,index2为num2起始下标,k为第k个
*/
private int getTopK(int[] nums1, int index1, int[] nums2, int index2, int k) {
if (index1 >= nums1.length) {
return nums2[index2 + k - 1];
}
if (index2 >= nums2.length) {
return nums1[index1 + k - 1];
}
if (k == 1) {
return Math.min(nums1[index1], nums2[index2]);
} else {
int tmpK = k / 2 - 1;
int position1 = Math.min((index1 + tmpK), nums1.length - 1);
int position2 = Math.min((index2 + tmpK), nums2.length - 1);
if (nums1[position1] >= nums2[position2]) {
position2 = position2 + 1;
k = k - (position2 - index2);
return getTopK(nums1, index1, nums2, position2, k);
} else {
position1 = position1 + 1;
k = k - (position1 - index1);
return getTopK(nums1, position1, nums2, index2, k);
}
}
}
/*
* @description: 5.最长回文子串,回文正反输出一样都字符串,例如aba
* @param: s:字符串
* @return: String:最长的回文子串
*/
public String longestPalindrome(String s) {
if (s == null || s.length() == 1) {
return s;
}
int n = s.length();
//dp[i][j]即为s(i,j)是否为回文字串
boolean[][] dp = new boolean[n][n];
int start = 0;
int end = 0;
//最外层为字符串长度
for (int l = 0; l < n; l++) {
for (int i = 0; i + l < n; i++) {
int j = i + l;
if (l == 0) {
dp[i][j] = true;
} else if (s.charAt(i) == s.charAt(j)) {
dp[i][j] = l == 1 || dp[i + 1][j - 1];
}
if (dp[i][j] && l + 1 > (end - start)) {
start = i;
end = i + 1 + l;
}
}
}
return s.substring(start, end);
}
/*
* @description: 6.Z字形变换,将一个给定字符串根据给定的行数,以从上往下、从左到右进行 Z 字形排列。
* @param: s:字符串,numRows:行数
* @return: String:Z变换后的字符串
*/
public String convert(String s, int numRows) {
if (numRows == 1) {
return s;
}
StringBuilder[] result = new StringBuilder[numRows];
for (int i = 0; i < numRows; i++) {
result[i] = new StringBuilder();
}
int count = 0;
boolean addFlag = true;
for (int i = 0, length = s.length(); i < length; i++) {
result[count].append(s.charAt(i));
if (addFlag) count++;
else count--;
if (count == numRows) {
addFlag = !addFlag;
count = count - 2;
}
if (count == -1) {
addFlag = !addFlag;
count = count + 2;
}
}
for (int i = 1; i < numRows; i++) {
result[0].append(result[i]);
}
return result[0].toString();
}
/*
* @description: 7.整数反转,如123反转321
* @param: x:整数
* @return: int:反转后的整数
*/
public int reverse(int x) {
int result = 0;
int tmpResult = 0;
int bit;
while (x != 0) {
bit = x % 10;
x = x / 10;
tmpResult = tmpResult * 10 + bit;
if (result != 0 && tmpResult / result < 10)
return 0;
result = tmpResult;
}
return result;
}
/*
* @description: 8.字符串转换整数 (atoi)
* @param: str:字符串,允许开头为空格,可能包含其他字符
* @return: int:字符串转换后的整数,如果超过32有符号整数的最值,就返回最值
*/
public int myAtoi(String str) {
int result = 0;
int tmpResult = 0;
int invalidResult = 0;
int positive = 1;
int start = 0;
int l = str.length();
//首先去除空格
for (; start < l; start++) {
if (str.charAt(start) != ' ')
break;
}
if (start == l) {
return invalidResult;
}
//判断首位是不是符号
int firstChar = str.charAt(start);
if (firstChar == '+') {
start++;
positive = 1;
} else if (firstChar == '-') {
start++;
positive = -1;
} else if (firstChar < '0' || firstChar > '9') {
return invalidResult;
}
for (; start < l; start++) {
char c = str.charAt(start);
//有效字符串
if (c >= '0' && c <= '9') {
tmpResult = tmpResult * 10 + (c - 48);//ascii码
//溢出情况
if (result != 0 && tmpResult / result < 10) {
if (positive == 1) {
return Integer.MAX_VALUE;
} else {
return Integer.MIN_VALUE;
}
}
result = tmpResult;
} else {
//无效字符串
break;
}
}
return positive * result;
}
/*
* @description: 9.回文数,判断一个数是否为回文数(字符串形式上)
* @param: x:整数
* @return: boolean:是否为回文数
*/
public boolean isPalindrome(int x) {
if (x == 0) {
return true;
}
//负数不可能为回文数
if (x < 0) {
return false;
}
//最后一位不能是0,例如10,100不可能是回文数
if (x % 10 == 0) {
return false;
}
int bit;
int result = 0;
while (x > 0) {
bit = x % 10;
result = result * 10 + bit;
if (result > x)
return false;
if (result == x)
return true;
x = x / 10;
if (result == x)
return true;
}
return true;
}
/*
* @description: 10.正则表达式匹配
* @param: s字符串,p正则表达式,
* s 可能为空,且只包含从 a-z 的小写字母。
* p 可能为空,且只包含从 a-z 的小写字母,以及字符 . 和 *。
* '.' 匹配任意单个字符
* '*' 匹配零个或多个前面的那一个元素
* @return: true匹配,false不匹配
*/
public boolean isMatch(String s, String p) {
if (p.isEmpty()) return s.isEmpty();
boolean firstCharMatch = (!s.isEmpty() &&
(p.charAt(0) == s.charAt(0) || p.charAt(0) == '.'));
//存在*时
if (p.length() >= 2 && p.charAt(1) == '*') {
//两种情况
//1 x*匹配空字符串
//2 x*匹配一个字符串
return (isMatch(s, p.substring(2)) ||
(firstCharMatch && isMatch(s.substring(1), p)));
} else {
//不存在*时
return firstCharMatch && isMatch(s.substring(1), p.substring(1));
}
}
/*
* @description: 11.盛最多水的容器
* @param: height:int数组,height[i]代表高度
* @return: int:最大的面积
*/
public int maxArea(int[] height) {
int left = 0, right = height.length - 1;
//初始面积
int max = Math.min(height[left], height[right]) * (right - left);
while (left < right) {
if (height[left] < height[right]) {
left++;
} else {
right--;
}
int tmpArea = Math.min(height[left], height[right]) * (right - left);
max = Math.max(max, tmpArea);
}
return max;
}
/*
* @description: 12.整数转罗马数字
* @param: num整数,在 1 到 3999 的范围内
* @return: 对应的罗马字符
* 字符 数值
* 字符 数值
* I 1
* V 5
* X 10
* L 50
* C 100
* D 500
* M 1000
*/
public String intToRoman(int num) {
String[] thousands = new String[]{"", "M", "MM", "MMM"};
//0,100,...,900
String[] hundreds = new String[]{"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
//0,10,...,90
String[] tens = new String[]{"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
//0,1,...,9
String[] ones = new String[]{"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};
//千位
int thousand = num / 1000;
int hundred = num % 1000 / 100;
int ten = num % 100 / 10;
int one = num % 10;
String result =
thousands[thousand] +
hundreds[hundred] +
tens[ten] +
ones[one];
return result;
}
/*
* @description: 13.罗马数字转整数
* @param: s:罗马数字字符串,在1到3999的范围内
* @return: int:s对应的数字
*/
public int romanToInt(String s) {
Map<Character, Integer> romanMap = initMap();
int result = 0;
int pre = 0;
for (int i = s.length() - 1; i >= 0; i--) {
int num = romanMap.get(s.charAt(i));
if (num >= pre) {
result += num;
} else {
result -= num;
}
pre = num;
}
return result;
}
/*
* @description: 初始化map
*/
private Map<Character, Integer> initMap() {
Map<Character, Integer> romanMap = new HashMap<>();
romanMap.put('I', 1);
romanMap.put('V', 5);
romanMap.put('X', 10);
romanMap.put('L', 50);
romanMap.put('C', 100);
romanMap.put('D', 500);
romanMap.put('M', 1000);
return romanMap;
}
/*
* @description: 14.最长公共前缀
* @param: strs:字符串数组
* @return: String:所有字符串最长公共前缀
*/
public String longestCommonPrefix(String[] strs) {
if (strs.length == 0) {
return "";
}
if (strs.length == 1) {
return strs[0];
}
//找出字符串最短长度
int minLength = Integer.MAX_VALUE;
for (String str : strs) {
minLength = Math.min(minLength, str.length());
}
for (int i = 0; i < minLength; i++) {
char c = strs[0].charAt(i);
for (int j = 1, l = strs.length; j < l; j++) {
if (strs[j].charAt(i) != c)
return strs[0].substring(0, i);
}
}
return strs[0].substring(0, minLength);
}
/*
* @description: 15.三数之和
* @param: nums:int数组
* @return: List<List<Integer>>:所有[a,b,c]使得a+b+c=0且a,b,c不重复
*/
public List<List<Integer>> threeSum(int[] nums) {
//三数之和可以转化为两数字之和,例如[-1, 0, 1, 2, -1, -4]只需要依次找到两个和为[1,0,-1,-2,1,4]即可
List<List<Integer>> result = new ArrayList<>();
//对数组进行排序
Arrays.sort(nums);
int length = nums.length;
for (int i = 0; i < length; i++) {
//若a已经大于0,由于排序过b,c肯定大于0
if (nums[i] > 0) {
break;
}
//相同的a直接跳过
if (i > 0 && (nums[i] == nums[i - 1])) {
continue;
}
int l = i + 1, r = length - 1;
while (l < r) {
int sum = nums[i] + nums[l] + nums[r];
//满足条件
if (sum == 0) {
List<Integer> list = new ArrayList<>();
list.add(nums[i]);
list.add(nums[l]);
list.add(nums[r]);
result.add(list);
while (l < r && (nums[l + 1] == nums[l])) l++;
while (l < r && (nums[r - 1] == nums[r])) r--;
l++;
r--;
}
//加大l
if (sum < 0) {
l++;
}
//减小r
if (sum > 0) {
r--;
}
}
}
return result;
}
/*
* @description: 使用回溯法解决,时间复杂度太高,应该优先使用双指针
*/
public List<List<Integer>> threeSum2(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
if (nums.length < 3) {
return result;
}
Arrays.sort(nums);
threeSum2(nums, 0, 0, new ArrayList<>(3), result);
return result;
}
public void threeSum2(int[] nums, int start, int sum, List<Integer> current, List<List<Integer>> result) {
if (current.size() == 3) {
if (sum == 0) {
result.add(new ArrayList<>(current));
}
return;
}
for (int i = start, l = nums.length; i < l; i++) {
//剪枝
//1.若a>0,b和c都大于0,不存在a+b+c=0
if (current.isEmpty() && nums[i] > 0)
break;
//1.若a+b>0,c大于0,不存在a+b+c=0
if (current.size() == 1 && (sum + nums[i]) > 0)
break;
//去重
if (i > start && nums[i] == nums[i - 1])
continue;
current.add(nums[i]);
threeSum2(nums, i + 1, sum + nums[i], current, result);
current.remove(current.size() - 1);
}
}
/*
* @description: 16.最接近的三数之和
* @param: nums:数组,target:目标值
* @return: int:最接近的target的三数之和
*/
public int threeSumClosest(int[] nums, int target) {
//排序
Arrays.sort(nums);
int length = nums.length;
int result = Integer.MAX_VALUE;
int minGap = Integer.MAX_VALUE;
for (int i = 0; i < length; i++) {
int l = i + 1, r = length - 1;
while (l < r) {
int sum = nums[i] + nums[l] + nums[r];
//相等时最接近,直接返回
if (sum == target) {
return target;
}
if (sum > target) {
r--;
}
if (sum < target) {
l++;
}
int gap = Math.abs(sum - target);
if (gap < minGap) {
result = sum;
minGap = gap;
}
}
}
return result;
}
/*
* @description: 17.电话号码的字母组合
* @param: digits:2-9组成的字符串
* @return: List<String>:九空格所有字符组合
* @example: digits为23,返回2对应的"abc"和3对应"def"的所有字符组合:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]
*/
public List<String> letterCombinations(String digits) {
List<String> result = new ArrayList<>();
List<List<String>> letterList = getList();
for (int i = 0, l = digits.length(); i < l; i++) {
List<String> charList = letterList.get(digits.charAt(i) - '0');
result = multiply(result, charList);
}
return result;
}
/*
* @description: 字符串数组转List
*/
private List<List<String>> getList() {
//0-9对应的九宫格
String[] letters = {
"", "", "abc",
"def", "ghi", "jkl",
"mno", "pqrs", "tuv",
"wxyz"
};
List<List<String>> letterList = new ArrayList(letters.length);
for (String letter : letters) {
List<String> charList = new ArrayList<>();
for (int j = 0, dl = letter.length(); j < dl; j++) {
charList.add(letter.charAt(j) + "");
}
letterList.add(charList);
}
return letterList;
}
/*
* @description: 笛卡尔积
*/
private List<String> multiply(List<String> l1, List<String> l2) {
if (l1.isEmpty() || l2.isEmpty()) {
return l1.isEmpty() ? l2 : l1;
}
List<String> result = new ArrayList<>();
for (int i = 0; i < l1.size(); i++)
for (int j = 0; j < l2.size(); j++) {
result.add(l1.get(i) + l2.get(j));
}
return result;
}
/*
* @description: 18.四数之和
* @param: nums:数组,target:目标值
* @return: List<List<Integer>>:所有[a,b,c,d]使得a+b+c=target且a,b,c,d不重复
*/
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> result = new ArrayList<>();
//对数组进行排序
Arrays.sort(nums);
int length = nums.length;
for (int i = 0; i < length - 1; i++) {
if (nums[i] > target) {
break;
}
if (i > 0 && (nums[i] == nums[i - 1])) {
continue;
}
for (int j = i + 1; j < length; j++) {
if (nums[i] + nums[j] > target) {
break;
}
if (j > i + 1 && (nums[j] == nums[j - 1])) {
continue;
}
int l = j + 1, r = length - 1;
while (l < r) {
int sum = nums[i] + nums[j] + nums[l] + nums[r];
if (sum == target) {
List<Integer> list = new ArrayList<>();
list.add(nums[i]);
list.add(nums[j]);
list.add(nums[l]);
list.add(nums[r]);
result.add(list);
while (l < r && (nums[l + 1] == nums[l])) l++;
while (l < r && (nums[r - 1] == nums[r])) r--;
l++;
r--;
}
//加大l
if ((target - sum) > 0) {
l++;
}
//减小r
if ((target - sum) < 0) {
r--;
}
}
}
}
return result;
}
/*
* @description: 19.删除链表的倒数第N个节点
* @param: head:链表头结点,n:待删除的倒数第n个,保证n是有效的
* @return: ListNode:返回删除后的头结点
*/
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode cursor = head;
//计算链表长度
int length = 0;
while (cursor != null) {
length++;
cursor = cursor.next;
}
//转换倒数为正数
int index = length - n;
//如果删除的是第一个,直接删除
if (index == 0) {
ListNode next = head.next;
head.next = null;
return next;
}
cursor = head;
ListNode pre = null;
while (index > 0) {
pre = cursor;
cursor = cursor.next;
index--;
}
pre.next = cursor.next;
return head;
}
/*
* @description: 双指针做法,只需要遍历1遍
*/
public ListNode removeNthFromEnd2(ListNode head, int n) {
ListNode newHead = new ListNode(0);
newHead.next = head;
ListNode fast = newHead;
ListNode slow = newHead;
while (n >= 0) {
fast = fast.next;
n--;
}
//第一个指针到达终点停止遍历
while (fast != null) {
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return newHead.next;
}
/*
* @description: 20.有效的括号
* @param: s:只包含括号()[]{}的字符串
* @return: boolean:s是否有效
*/
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for (int i = 0, l = s.length(); i < l; i++) {
char c = s.charAt(i);
if (stack.isEmpty() || isLeft(c)) {
stack.push(c);
} else {
if (stack.peek() == getRight(c)) {
stack.pop();
} else {
break;
}
}
}
return stack.isEmpty();
}
private boolean isLeft(char c) {
return c == '(' || c == '[' || c == '{';
}
private char getRight(char c) {
if (c == ')')
return '(';
if (c == ']')
return '[';
return '{';
}
/*
* @description: 21.合并两个有序链表
* @param: l1,l2:有序链表
* @return: ListNode:合并后的链表
*/
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode head = new ListNode(0);
ListNode cursor = head;
while (l1 != null || l2 != null) {
if (l1 == null) {
cursor.next = new ListNode(l2.val);
l2 = l2.next;
} else if (l2 == null) {
cursor.next = new ListNode(l1.val);
l1 = l1.next;
} else {
if (l1.val < l2.val) {
cursor.next = new ListNode(l1.val);
l1 = l1.next;
} else {
cursor.next = new ListNode(l2.val);
l2 = l2.next;
}
}
cursor = cursor.next;
}
return head.next;
}
/*
* @description: 22.括号生成
* @param: n::括号对数
* @return: List<String>:所有有效的可能性组合数
*/
public List<String> generateParenthesis(int n) {
List<String> result = new ArrayList<>();
generateParenthesis(n, 0, 0, "", result);
return result;
}
/*
* @description: 生成括号,n:括号对数,l:左括号数,r:右括号数,s:当前字符串,result:结果集
*/
private void generateParenthesis(int n, int l, int r, String s, List<String> result) {
if (l == n && r == n) {
result.add(s);
}
if (l < n) {
generateParenthesis(n, l + 1, r, s + "(", result);
}
if (r < l) {
generateParenthesis(n, l, r + 1, s + ")", result);
}
}
/*
* @description: 23.合并K个升序链表
* @param: lists链表数组
* @return: 合并后链表头
*/
public ListNode mergeKLists(ListNode[] lists) {
if (lists.length == 0) {
return null;
}
if (lists.length == 1) {
return lists[0];
}
List<Integer> nodeList = new ArrayList<>();
for (int i = 0; i < lists.length; i++) {
ListNode head = lists[i];
while (head != null) {
nodeList.add(head.val);
head = head.next;
}
}
Collections.sort(nodeList);
ListNode head = new ListNode(0);
ListNode current = head;
for (int i = 0; i < nodeList.size(); i++) {
ListNode node = new ListNode(nodeList.get(i));
current.next = node;
current = node;
}
return head.next;
}
/*
* @description: 使用2路归并合并
*/
public ListNode mergeKLists2(ListNode[] lists) {
if (lists.length == 0) {
return null;
}
if (lists.length == 1) {
return lists[0];
}
return merge(lists, 0, lists.length - 1);
}
private ListNode merge(ListNode[] lists, int l, int r) {
if (l == r) {
return lists[l];
}
if (l + 1 == r) {
return mergeTwoLists(lists[l], lists[r]);
}
int mid = (l + r) / 2;
ListNode l1 = merge(lists, l, mid);
ListNode l2 = merge(lists, mid + 1, r);
return mergeTwoLists(l1, l2);
}
/*
* @description: 24.两两交换链表中的节点
* @param: head链表头
* @return: ListNode:交换后的链表
*/
public ListNode swapPairs(ListNode head) {
//链表只有0个或1个结点时,无法交换
if (head == null || head.next == null) {
return head;
}
// ListNode current = head;
ListNode next = head.next;
head.next = swapPairs(next.next);
next.next = head;
return next;
}
/*
* @description: 非递归实现
*/
public ListNode swapPairs2(ListNode head) {
//链表只有0个或1个结点时,无法交换
if (head == null || head.next == null) {
return head;
}
ListNode next = head.next;
head.next = swapPairs(next.next);
next.next = head;
return next;
}
/*
* @description: 25.K个一组翻转链表
* @param: head链表头结点,k数量
* @return: ListNode:翻转后的链表
*/
public ListNode reverseKGroup(ListNode head, int k) {
if (head == null || head.next == null || k == 0) {
return head;
}
ListNode index = head;
int i = k;
while (i - 1 > 0) {
index = index.next;
if (index == null) {
return head;
}
i--;
}
ListNode temp = index.next;
index.next = null;
ListNode newHead = reverse(head);
head.next = reverseKGroup(temp, k);
return newHead;
}
/*
* @description: 翻转链表
*/
private ListNode reverse(ListNode head) {
ListNode newHead = head;
while (head.next != null) {
ListNode next = head.next;
head.next = next.next;
next.next = newHead;
newHead = next;
}
return newHead;
}
/*
* @description: 26.删除排序数组中的重复项
* @param: nums:排序数组
* @return: int:删除重复元素后的数组长度
*/
public int removeDuplicates(int[] nums) {
if (nums.length < 2) {
return nums.length;
}
int slow = 0;
for (int fast = 1, l = nums.length; fast < l; fast++) {
if (nums[fast] != nums[slow]) {
slow++;
if (fast != slow) {
nums[slow] = nums[fast];
}
}
}
//slow是下标,数量应该再加1
return slow + 1;
}
/*
* @description: 27. 移除元素
* @param: nums:数组, val:需要移除的元素
* @return: int: 移除val元素后的数组长度
*/
public int removeElement(int[] nums, int val) {
int slow = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] != val) {
if (i != slow) {
int temp = nums[slow];
nums[slow] = nums[i];
nums[i] = temp;
}
slow++;
}
}
return slow;
}
//todo 28
/*
* @description: 29.两数相除
* @param: dividend被除数,divisor除数
* @return: 商(取整)
*/
public int divide(int dividend, int divisor) {
int ans = -1;
int sign = 1;
if (dividend > 0) {
sign = opposite(sign);
dividend = opposite(dividend);
}
if (divisor > 0) {
sign = opposite(sign);
divisor = opposite(divisor);
}
//由于被除数和除数都是负数,如果dividend>divisor
//说明|dividend|<|divisor|
//即|dividend|/|divisor| < 1,结果就是0