Leetcode Question 23: Merge k Sorted Lists

Keywords: Python

Topic address: Merge k Sorted Lists

Topic Introduction:

Merge K sorting lists and return the merged sorting list. Please analyze and describe the complexity of the algorithm.

Example:

Input:
[
  1->4->5,
  1->3->4,
  2->6
]
Output: 1->1->2->3->4->4->5->6

Topic Analysis:

1. The first thing to think about is violence. Find an array to store the data in the linked list (time complexity is O(n). Then sort the array and put the array back into a new linked list. Then return the result.

C++ Code:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    int nums[5000];
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        int sizeNum = lists.size();
        ListNode *ans, *temp;
        ans = new ListNode(0);
        int flag = 0;
        for (int i = 0; i < sizeNum; i++)
        {
            temp = lists[i];
            while (temp != NULL)
            {
                nums[flag++] = temp -> val;
                temp = temp -> next;
            }
        }
        sort(nums,nums + flag);
        temp = ans;
        
        for (int i = 0; i < flag; i++)
        {
            temp -> next = new ListNode(nums[i]);
            temp = temp -> next;
            
        }
        return ans -> next;
    }
};

Python code:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def mergeKLists(self, lists: List[ListNode]) -> ListNode:
        sizeNum = len(lists)
        flag = 0
        nums = [1 << 31] * 10000
        for i in range(sizeNum):
            temp = lists[i]
            while(temp != None):
                nums[flag] = temp.val
                flag += 1
                temp = temp.next
        
        nums.sort()
        temp = ans = ListNode(0)
        
        for i in range (flag):
            temp.next = ListNode(nums[i])
            temp = temp.next
            
        return ans.next
        

 

Posted by vombomin on Sat, 16 Mar 2019 18:24:27 -0700