Write an efficient algorithm that searches for a value inMXNMatrix. 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, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50]
GivenTarget=3
, ReturnTrue
.
Original question link: https://oj.leetcode.com/problems/search-a-2d-matrix/
Question: Check whether the target value exists in the M * n matrix.
A better solution is binary search, which treats the entire matrix as an array.
Public Boolean searchmatrix (INT [] [] matrix, int target) {If (matrix = NULL | matrix. length = 0 | matrix [0]. length = 0) return false; int M = matrix. length; int n = matrix [0]. length; int start = 0; int end = m * n-1; while (start <= END) {int mid = (start + end)/2; int x = mid/N; int y = mid % N; If (Matrix [x] [Y] = target) return true; if (Matrix [x] [Y] <target) Start = Mid + 1; elseend = mid-1;} return false ;}
Leetcode -- search a 2D matrix