# Question

Formatted question description: https://leetcode.ca/all/240.html

 Write an efficient algorithm that searches for a value in an m x n matrix. This 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.

For example,

Consider the following 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]
]

Given target = 5, return true.

Given target = 20, return false.

@tag-binarysearch


# Algorithm

It is an extension of the previous 74. Search a 2D Matrix.

74. Search a 2D Matrix is that the first number of each line is greater than the last number of the previous line. So for that question, you can expand the two-dimensional array into a one-bit array with a two-check search.

And this question has two unique numbers, the lower left corner and the upper right corner. The 18 in the lower left corner of above example, all the numbers going up become smaller, and all the numbers going to the right increase, then we can compare with the target number,

• If the number of targets is large, search to the right,
• If the target number is small, search upwards.

In this way, it can be judged whether the target number exists. Of course, we can also put the starting number in the upper right corner, search left and down, and set the stop condition correctly.

valid in Search_a_2D_Matrix, but not in II

{1, 4, 7, 11, 15},
{2, 5, 8, 12, 19},


Please refer to this comment, which is awesome https://leetcode.com/problems/search-a-2d-matrix-ii/discuss/66140/My-concise-O(m+n)-Java-solution/68155 .

• Java