題目放一下:
思路分析:
舉例分析一波:
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版是我本身寫的,有興趣能夠關注花花醬老師,講的很好~圖片