Search a 2D Matrix Total Accepted: 35062 Total Submissions: 111591
Write an efficient algorithm, searches for a value in a m x n Matrix. This matrix has the following properties:
- Integers in each row is sorted from the left to the right.
- The first integer of each row was greater than the last integer of the previous row.
For example,
Consider the following matrix:
[ [1, 3, 5, 7], [Ten, One,], [23, 30, 34, 50]]
Given Target = 3
, returntrue
MySolution:
Boolsearchmatrix (int **matrix, int m, int n, int target) {//m = 3,n=1; matrix[[1,1]],target=0; [[ -10],//[-7],//[-5]], -10 int i; Int J; int inhalf = 0; if (M <=0 | | n <= 0) return false; if (M <= 1 && n <= 1) {return matrix[m-1][n-1] = = target; } inhalf = (int) (N/2)-1; if (n <= 1) {inhalf = 0; } if (Target < matrix[0][0] | | target > MATRIX[M-1][N-1]) return false; for (i = 0; i < m; i++) {if (target >= matrix[i][0] && target <= matrix[i][n-1]) { if (target <= matrix[i][inhalf])/* N/2 */{for (j = 0; J <=InHalf; J + +) {if (target = = Matrix[i][j]) return true; }} else/* target >= matrix[i][inhalf] */{for (j = inhalf+1; J <= n-1; J + +) {if (target = = Matrix[i][j]) return true; }}}} return false;}
Submission result:accepted Address:
Search a 2D Matrix
Search a 2D Matrix