Selection algorithms on sorted matrix

后端 未结 8 1786
野性不改
野性不改 2020-11-28 22:51

this is a google interview question :

Given a N*N Matrix. All rows are sorted, and all columns are sorted. Find the Kth Largest element of the matrix.

doing

8条回答
  •  不知归路
    2020-11-28 23:04

    You do a breath first search starting at the (0,0). (0,0)’s 2 children (0,1) & (1,0) are added to the potential candidates list for the 2nd element. Loop picking the smallest element in the potential candidates list to be the next element, add it’s children to the potential candidates list. Stop when find the kth element.

    Make the potential candidates list a min heap. The heap will never be bigger than n+m.

    Also you could do the reverse from the last element (n,m) if k is greater than n*m/2.

    Worst Case: this would be n*m/2 lg(n + m), instead of n*m lg(n * m) of sorting.

提交回复
热议问题