File tree 1 file changed +10
-13
lines changed
1 file changed +10
-13
lines changed Original file line number Diff line number Diff line change @@ -56,23 +56,20 @@ \subsubsection{分析}
56
56
\subsubsection {代码 }
57
57
\begin {Code }
58
58
//LeetCode, Merge Two Sorted Lists
59
- // 时间复杂度O(m+n ),空间复杂度O(1)
59
+ // 时间复杂度O(min(m,n) ),空间复杂度O(1)
60
60
class Solution {
61
61
public:
62
62
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; }
74
70
}
75
- return head.next;
71
+ p->next = l1 != nullptr ? l1 : l2;
72
+ return h.next;
76
73
}
77
74
};
78
75
\end {Code }
You can’t perform that action at this time.
0 commit comments