File tree Expand file tree Collapse file tree 1 file changed +10
-13
lines changed Expand file tree Collapse file tree 1 file changed +10
-13
lines changed Original file line number Diff line number Diff line change @@ -56,23 +56,20 @@ \subsubsection{分析}
5656\subsubsection {代码 }
5757\begin {Code }
5858//LeetCode, Merge Two Sorted Lists
59- // 时间复杂度O(m+n ),空间复杂度O(1)
59+ // 时间复杂度O(min(m,n) ),空间复杂度O(1)
6060class Solution {
6161public:
6262 ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
63- ListNode head(-1);
64- for (ListNode* p = &head; l1 != nullptr || l2 != nullptr; p = p->next) {
65- int val1 = l1 == nullptr ? INT_MAX : l1->val;
66- int val2 = l2 == nullptr ? INT_MAX : l2->val;
67- if (val1 <= val2) {
68- p->next = l1;
69- l1 = l1->next;
70- } else {
71- p->next = l2;
72- l2 = l2->next;
73- }
63+ if (l1 == nullptr) return l2;
64+ if (l2 == nullptr) return l1;
65+ ListNode h(-1);
66+ ListNode *p = &h;
67+ for (; l1 != nullptr && l2 != nullptr; p = p->next) {
68+ if (l1->val > l2->val) { p->next = l2; l2 = l2->next; }
69+ else { p->next = l1; l1 = l1->next; }
7470 }
75- return head.next;
71+ p->next = l1 != nullptr ? l1 : l2;
72+ return h.next;
7673 }
7774};
7875\end {Code }
You can’t perform that action at this time.
0 commit comments