74\. Search a 2D Matrix

# 74. Search a 2D Matrix (opens new window)

# Description

Difficulty: Medium

Related Topics: Array (opens new window), Binary Search (opens new window), Matrix (opens new window)

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

  • Integers in each row are sorted from left to right.
  • The first integer of each row is greater than the last integer of the previous row.

Example 1:

Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
Output: true
1
2

Example 2:

Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13
Output: false
1
2

Constraints:

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 100
  • -104 <= matrix[i][j], target <= 104

# Solution

Language: JavaScript

/**
 * @param {number[][]} matrix
 * @param {number} target
 * @return {boolean}
 */
var searchMatrix = function(matrix, target) {
    let [i, j] = [matrix.length - 1, 0];
    
    while (i >= 0 && j < matrix[0].length) {
        if (matrix[i][j] === target) return true;
        
        matrix[i][j] > target ? i-- : j++;
    }
    
    return false;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
上次更新: 2022/7/14 下午7:06:25