Search a 2D Matrix
Total Accepted: 35062 Total Submissions: 111591
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, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ]
Given target = 3
, return true
MySolution :
bool searchMatrix(int **matrix, int m, int n, int target) { 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
RunTime:
在做这个题目的时候遇到了一个初始化问题。代码例如以下:
#include <stdio.h> #include <stdlib.h> #define bool int #define false 0 #define true 1 bool searchMatrix(int **matrix, int m, int n, int target); bool searchMatrix(int **matrix, int m, int n, int target) { int i; int j; int InHalf = 0; InHalf = (int)(n/2)-1; for( i = 0; i < 3; i++ ) for( j = 0; j < 4; j++) printf("%d ",matrix[i][j]); 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; } int main(void) { int i; int m=3,n=4; int iReturn = false; int** pMatrix2D = malloc( sizeof( int* )*m ); pMatrix2D[0] = malloc( sizeof( int )*m*n ); for( i = 1; i < 3; i++) { pMatrix2D[i] = pMatrix2D[i-1] + 4; } pMatrix2D[0][0] = 1; pMatrix2D[0][1] = 3; pMatrix2D[0][2] = 5; pMatrix2D[0][3] = 7; pMatrix2D[1][0] = 10; pMatrix2D[1][1] = 11; pMatrix2D[1][2] = 16; pMatrix2D[1][3] = 20; pMatrix2D[2][0] = 23; pMatrix2D[2][1] = 30; pMatrix2D[2][2] = 34; pMatrix2D[2][3] = 50; iReturn = searchMatrix( pMatrix2D, m, n, 3 ); printf( "%d ",iReturn ); return 0; }
问题參考