- Search a 2D Matrix
Search a 2D Matrix
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 from left to right.
* The first integer of each row is greater than the last integer of the previous row.
For example,
Consider the following matrix:
1. [
2. [1, 3, 5, 7],
3. [10, 11, 16, 20],
4. [23, 30, 34, 50]
5. ]
Given target = 3, return true.
Solution:
1. public class Solution {
2. public boolean searchMatrix(int[][] matrix, int target) {
3. int n = matrix.length;
4. int m = matrix[0].length;
5. 6. int i = 0;
7. int j = m - 1;
8. 9. while (i < n && j >= 0) {
10. if (target == matrix[i][j]) {
11. return true;
12. }
13. 14. if (target < matrix[i][j]) {
15. j--;
16. } else {
17. i++;
18. }
19. }
20. 21. return false;
22. }
23. }
