Created
September 3, 2014 06:07
-
-
Save xiren-wang/794c0da0bbae41cd742e to your computer and use it in GitHub Desktop.
search a 2D matrix
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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. | |
*/ | |
class Solution { | |
public: | |
bool searchMatrix(vector<vector<int> > &matrix, int target) { | |
//search from top right, if larger, search downward, else, left | |
int m = matrix.size(); | |
if (m <= 0) | |
return false; | |
int n = matrix[0].size(); | |
int row = 0; | |
int col = n-1; | |
while ( row < m && col >=0 ) { | |
while (col >= 0 && matrix[row][col] > target) | |
col --; | |
if (col < 0) | |
return false; | |
while (row < m && matrix[row][col] < target ) | |
row ++; | |
if (row >= m) | |
return false; | |
if (matrix[row][col] == target ) | |
return true; | |
} | |
return false; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment