Selection algorithms on sorted matrix

后端 未结 8 1775
野性不改
野性不改 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:20

    Based on N, you can find the diagonal where the element is located. For example in the matrix,

     1   5   7  12
     3   6   8  14
     4   9  10  15
    11  17  19  20
    

    You can deduce the diagonal by determining the total # of elements in the previous diagonals,

    /diagonal#/elements/# of elements/cumulative # of elements/
    /d1/ 1         / 1 / 1 /
    /d2/ 3 5       / 2 / 1+2 = 3 /
    /d3/ 4 6 7     / 3 / 1+2+3 = 6 /
    /d4/ 11 9 8 12 / 4 / 1+2+3+4 = 10 /
    /d5/ 17 10 14  / 3 /
    /d6/ 19 15     / 2 /
    /d7/ 20        / 1 /
    

    The reason why we need to find the diagonal is because the diagonals above will always have elements lesser than any of the current diagonal elements and the diagonals below will always have elements greater than any of the current diagonal elements.

    So, you can be sure that diagonal d4 has the required element(Since it contains 7th largest to 10th largest). Since until the previous diagonal there were 6 elements, you just need to find the 4th largest element in diagonal d4.

提交回复
热议问题