Skip to content

Instantly share code, notes, and snippets.

@sundeepblue
Created May 10, 2014 20:53
Show Gist options
  • Select an option

  • Save sundeepblue/f48a65440bbc121d6a65 to your computer and use it in GitHub Desktop.

Select an option

Save sundeepblue/f48a65440bbc121d6a65 to your computer and use it in GitHub Desktop.
Search a 2D Matrix
bool search_matrix(vector<vector<int>> &matrix, int target) {
if(matrix.empty()) return false;
int m = matrix.size(), n = matrix[0].size();
if(target < matrix[0][0] || target > matrix[m-1][n-1]) return false;
int r = 0, c = n-1;
while(r < m && c >= 0) {
if(target == matrix[r][c]) return true;
else if(target < matrix[r][c]) c--;
else r++;
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment