Monday, March 05, 2018

find x in sorted matrix

Find x in sorted matrix (last element of row is less than first element of next row).
(row, col) find(matrix, x):
    if matrix == null
        || matrix.length() == 0
        || matrix[0].length() == 0:
        throw
    rows = matrix.length()
    cols = matrix[0].length()
    len = rows * cols
    start = 0, end = len -1
    while start <= end:
        mid = start + (end - start)/2
        i, j = toij(mid, cols)
        if x < matrix[i][j]:
            end = mid -1
        else if matrix[i][j] < x:
            start = mid +1
        else:
            return (i, j)
    return null

(i, j) toij(mid, cols):
    return (mid /cols, mid %cols)
[Hat tip to DJ]

No comments:

Post a Comment