Skip to content

Latest commit

 

History

History
34 lines (28 loc) · 1.05 KB

Search a 2D Matrix II.md

File metadata and controls

34 lines (28 loc) · 1.05 KB

Write an efficient algorithm that searches for a target value in an m x n integer matrix. The matrix has the following properties:

Integers in each row are sorted in ascending from left to right. Integers in each column are sorted in ascending from top to bottom.

Screen Shot 2021-12-17 at 21 51 06

Screen Shot 2021-12-17 at 21 51 30

Time complexity O(n + m)

/**
 * @param {number[][]} matrix
 * @param {number} target
 * @return {boolean}
 */
var searchMatrix = function(matrix, target) {
    let row = 0, col = matrix[0].length - 1;
    while(row < matrix.length && col >= 0) {
        if(matrix[row][col] === target) {
            return true;
        }
        else if(matrix[row][col] < target) {
            row++;
        }
        else {
            col--
        }
    }
    return false
};