Merge K Sorted Arrays

Array, Heap, Priority Queue

Description

Given _k _sorted integer arrays, merge them into one sorted array.

Example

Example 1:

Input: 
  [
    [1, 3, 5, 7],
    [2, 4, 6],
    [0, 8, 9, 10, 11]
  ]
Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

Example 2:

Input:
  [
    [1,2,3],
    [1,2]
  ]
Output: [1,1,2,2,3]

Challenge

Do it in O(N log k).

  • _N - _is the total number of integers.

  • _k - _is the number of arrays.

Solution

LintCode official - Heap (Priority Queue)

可以用堆做到 O(N log k) 的时间复杂度.

初始将所有数组的首个元素入堆, 并记录入堆的元素是属于哪个数组的.

每次取出堆顶元素, 并放入该元素所在数组的下一个元素.

Divide and Conquer

Last updated

Was this helpful?