题目放一下:
思路分析:
举例分析一波:
l1和l2是要合并的两个链表,m是最后组合而成的链表
java
上代码:
首先是C++的:
使用链表:
数组
class Solution { public: ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { ListNode dummy(0); ListNode* tail = &dummy; while(l1 && l2) { if (l1->val < l2->val) { tail->next = l1; l1 = l1->next; } else { tail->next = l2; l2 = l2->next; } tail = tail->next; } if (l1) tail->next = l1; if (l2) tail->next = l2; return dummy.next; } };
若是使用递归的话:
merge(a, b)
= a if b is empty
= b if a is empty
=a[0] + merge(a[1], b) if a[0] < b[0]
=b[0] + merge(a, b[1]) if a[0] > b[0]
spa
使用递归:3d
class Solution { public: ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { ListNode dummy(0); ListNode* tail = &dummy; while(l1 && l2) { if (l1->val < l2->val) { tail->next = l1; l1 = l1->next; } else { tail->next = l2; l2 = l2->next; } tail = tail->next; } if (l1) tail->next = l1; if (l2) tail->next = l2; return dummy.next; } };
而后是java的:
使用链表
code
class Solution { public ListNode mergeTwoLists(ListNode l1, ListNode l2) { ListNode l3 = new ListNode(0); ListNode tail = l3; if (l1 == null) { return l2; } if (l2 == null) { return l1; } while ((l1 != null) && (l2 != null)) { if (l1.val < l2.val) { tail.next = l1; l1 = l1.next; } else { tail.next = l2; l2 = l2.next; } tail = tail.next; } if (l1 == null) { tail.next = l2; } if (l2 == null) { tail.next = l1; } return l3.next; } }
使用递归方法:
视频
class Solution { public ListNode mergeTwoLists(ListNode l1, ListNode l2) { if (l1 == null) return l2; if (l2 == null) return l1; if (l1.val < l2.val) { l1.next = mergeTwoLists(l1.next, l2); return l1; } else { l2.next = mergeTwoLists(l1, l2.next); return l2; } } }
时间复杂度分析:
使用链表的话
T(n) = 1 + T(n-1)
= O(n)
blog
使用数组的话
T(n) = n + T(n-1)
= O(n^2)
递归
这篇文章的C++版是参照B站的up主花花酱老师的视频写的,java版是我本身写的,有兴趣能够关注花花酱老师,讲的很好~图片