Created
May 10, 2014 20:53
-
-
Save sundeepblue/f48a65440bbc121d6a65 to your computer and use it in GitHub Desktop.
Search a 2D Matrix
This file contains hidden or 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
| 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