File tree Expand file tree Collapse file tree 2 files changed +75
-0
lines changed
Expand file tree Collapse file tree 2 files changed +75
-0
lines changed Original file line number Diff line number Diff line change 2121* [ 18. 4Sum] ( leetCode-18-4Sum.md )
2222* [ 19. Remove Nth Node From End of List] ( leetCode-19-Remov-Nth-Node-From-End-of-List.md )
2323* [ 20. Valid Parentheses] (leetCode-20-Valid Parentheses.md)
24+ * [ 21. Merge Two Sorted Lists] ( leetCode-21-Merge-Two-Sorted-Lists.md )
2425* [ 79. Word Search] ( leetCode-79-Word-Search.md )
Original file line number Diff line number Diff line change 1+ # 题目描述(简单难度)
2+
3+ ![ ] ( https://windliang.oss-cn-beijing.aliyuncs.com/21.jpg )
4+
5+ 合并两个有序链表。
6+
7+ # 解法一 迭代
8+
9+ 遍历两个链表。
10+
11+ ``` java
12+ public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
13+ ListNode h = new ListNode (0 );
14+ ListNode ans= h;
15+ while (l1 != null && l2 != null ) {
16+ if (l1. val < l2. val) {
17+ h. next = l1;
18+ h = h. next;
19+ l1 = l1. next;
20+ } else {
21+ h. next = l2;
22+ h = h. next;
23+ l2 = l2. next;
24+ }
25+ }
26+ if (l1== null ){
27+ while (l2!= null ){
28+ h. next= l2;
29+ l2= l2. next;
30+ h= h. next;
31+ }
32+ }
33+ if (l2== null ){
34+ while (l1!= null ){
35+ h. next= l1;
36+ l1= l1. next;
37+ h= h. next;
38+ }
39+ }
40+ h. next= null ;
41+ return ans. next;
42+ }
43+ ```
44+
45+ 时间复杂度:O(m + n)。
46+
47+ 空间复杂度:O(1)。
48+
49+ # 解法二 递归
50+
51+ 参考[ 这里] (Merge Two Sorted Lists)
52+
53+ ``` java
54+ ListNode mergeTwoLists(ListNode l1, ListNode l2) {
55+ if (l1 == null ) return l2;
56+ if (l2 == null ) return l1;
57+
58+ if (l1. val < l2. val) {
59+ l1. next = mergeTwoLists(l1. next, l2);
60+ return l1;
61+ } else {
62+ l2. next = mergeTwoLists(l2. next, l1);
63+ return l2;
64+ }
65+ }
66+ ```
67+
68+ 时间复杂度:
69+
70+ 空间复杂度:
71+
72+ # 总
73+
74+ 递归看起来,两个字,优雅!但是关于递归的时间复杂度,空间复杂度的求法,先留个坑吧。
You can’t perform that action at this time.
0 commit comments