Search A 2D Matrix II Problem


Description

LeetCode Problem 240.

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.

Example 1:

1
2
Input: matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 5
Output: true

Example 2:

1
2
Input: matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 20
Output: false

Constraints:

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= n, m <= 300
  • -10^9 <= matrix[i][j] <= 10^9
  • All the integers in each row are sorted in ascending order.
  • All the integers in each column are sorted in ascending order.
  • -10^9 <= target <= 10^9


Sample C++ Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        int row = matrix.size();
        if (row == 0) return false;
        int col = matrix[0].size();
        if (col == 0) return false;
        
        int l, r, m, pos;
        
        for (int i = 0; i < row; i ++) {
            l = 0, r = col-1;
            while (l <= r) {
                m = (l + r) / 2;
                if (matrix[i][m] == target)
                    return true;
                if (matrix[i][m] < target)
                    l = m + 1;
                else
                    r = m - 1;
                pos = m;
            }
            if (matrix[i][pos] == target)
                return true;
        }
        return false;
    }
};




Related Posts

Find K-Th Smallest Pair Distance Problem

LeetCode 719. The distance of a pair of integers a...

Binary Search Problem

LeetCode 704. Given an array of integers nums which is...

Random Point In Non-Overlapping Rectangles Problem

LeetCode 497. You are given an array of non-overlapping axis-aligned...

Split Array Largest Sum Problem

LeetCode 410. Given an array nums which consists of non-negative...

Smallest Good Base Problem

LeetCode 483. Given an integer n represented as a string,...

Single Element In A Sorted Array Problem

LeetCode 540. You are given a sorted array consisting of...