Skip to content

Instantly share code, notes, and snippets.

@xiren-wang
Created September 3, 2014 06:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xiren-wang/794c0da0bbae41cd742e to your computer and use it in GitHub Desktop.
Save xiren-wang/794c0da0bbae41cd742e to your computer and use it in GitHub Desktop.
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, 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