23.Merge-k-Sorted-Lists

23. Merge k Sorted Lists

题目地址

https://leetcode.com/problems/merge-k-sorted-lists/

https://www.lintcode.com/problem/merge-k-sorted-lists/description

题目描述

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

Example:
Input:
[
  1->4->5,
  1->3->4,
  2->6
]
Output: 1->1->2->3->4->4->5->6 Given a string s, cut s into some substrings such that every substring is a palindrome.

Return the minimum cuts needed for a palindrome partitioning of s.

代码

Approach 1: Divide & Conquer

Approach 2: PriorityQueue

Approach 3: Merge two by two

Approach 5: Brute Force

Intuition

  • Traverse all the linked lists and collect the values of the nodes into an array.

  • Sort and iterate over this array to get the proper value of nodes.

  • Create a new sorted linked list and extend it with the new nodes.

  • Time complexity : O_(_N_log_N) where N is the total number of nodes.

    • Collecting all the values costs O_(_N) time.

    • A stable sorting algorithm costs O_(_N_log_N) time.

    • Iterating for creating the linked list costs O_(_N) time.

  • Space complexity : O(N).

    • Sorting cost O(N) space (depends on the algorithm you choose).

    • Creating a new linked list costs O(N) space.

Last updated

Was this helpful?