🙆

LeetCode #21 Merge Two Sorted Lists

2024/10/17に公開

問題概要

入力値:list1(Optional[ListNode]), list2(Optional[ListNode])
出力値:Optional[ListNode]
Merge the two lists into one sorted list. The list should be made by splicing together the nodes of the first two lists.
問題のリンク

入力例

Input: list1=[1,2,4], list2=[1,3,4]
Output: [1,1,2,3,4,4]

解答例1

計算量:O(n)
Python

class Solution(object):
    def mergeTwoLists(self, list1, list2):
        """
        :type list1: Optional[ListNode]
        :type list2: Optional[ListNode]
        :rtype: Optional[ListNode]
        """
        dummy = current = ListNode()
        while list1 and list2:
            val_1 = list1.val
            val_2 = list2.val
            if val_1 <= val_2:
                current.next = list1
                list1 = list1.next
            else:
                current.next = list2
                list2 = list2.next
            current = current.next
        if list1:
            current.next = list1
        if list2:
            current.next = list2
        return dummy.next

Runtime: 18ms
Beats: 66.75%

C++

class Solution {
public:
    ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
        ListNode* dummy = new ListNode();
        ListNode* current = dummy;
        while (list1 && list2) {
            if (list1->val <= list2->val) {
                current->next = list1;
                list1 = list1->next;
            } else {
                current->next = list2;
                list2 = list2->next;
            }
            current = current->next;
        }
        if (list1) {
            current->next = list1;
        }
        if (list2) {
            current->next = list2;
        }
        return dummy->next;
    }
};

Runtime: 7ms
Beats: 41.28%

Discussion