Kth smallest element in sorted matrix

后端 未结 9 2191
被撕碎了的回忆
被撕碎了的回忆 2020-12-23 14:43

This is an interview question.

Find the Kth smallest element in a matrix with sorted rows and columns.
Is it correct that the Kth small

9条回答
  •  攒了一身酷
    2020-12-23 15:38

    O(k log(k)) solution.

    • Build a minheap.

    • Add (0,0) to the heap. While, we haven't found the kth smallest element, remove the top element (x,y) from heap and add next two elements [(x+1,y) and (x,y+1)] if they haven't been visited before.

    We are doing O(k) operations on a heap of size O(k) and hence the complexity.

提交回复
热议问题