8000 update mergeTwoLists solution, time complexity changed to O(min(m.n)) · learningpro/leetcode@2d1a7c9 · GitHub
[go: up one dir, main page]

Skip to content

Commit 2d1a7c9

Browse files
committed
update mergeTwoLists solution, time complexity changed to O(min(m.n))
1 parent 60b7fbe commit 2d1a7c9

File tree

1 file changed

+10
-13
lines changed

1 file changed

+10
-13
lines changed

C++/chapSorting.tex

+10-13
Original file line numberDiff line numberDiff 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)
6060
class Solution {
6161
public:
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}

0 commit comments

Comments
 (0)
0