378. Kth Smallest Element in a Sorted Matrix

Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix.
Note that it is the kth smallest element in the sorted order, not the kth distinct element.
Example:
matrix = [ [ 1, 5, 9], [10, 11, 13], [12, 13, 15]]
k = 8
return 13.

**Note: **You may assume k is always valid, 1 ≤ k ≤ n2
由于二维数组行和列都是有序的,所以左上角的元素是最小的,右下角的元素是最大的。
我们从这两个元素开始,使用二分法查找,取这两个元素的中间值,看看数组里有多少个元素小于等于它,如果少于k就在后半部分里找,如果多于k就从前半部分里找。

var kthSmallest = function(matrix, k) {
    var n = matrix.length;
    var le = matrix[0][0], ri = matrix[n - 1][n - 1];
    var mid = 0;
    while (le < ri)
    {
        mid = parseInt(le + (ri-le)/2);
        var num = 0;
        for (var i = 0; i < n; i++)
        {
            var pos = 0;
            for (var j = 0;j < n;j++) {
                if (matrix[i][j]<=mid) 
                    pos = j+1;
                else 
                    break;
            }
            num += pos;
        }
        if (num < k)
            le = mid + 1;
        else
            ri = mid;
    }
    return le;
};

你可能感兴趣的:(378. Kth Smallest Element in a Sorted Matrix)