- if curr < target,那么所在的那一行就可以排除,因为那一行所有的数全部小于等于curr,target不可能在其中
- 相同的,if curr > target,那么curr所在的那一列就可以排除
- if curr == target, return true
时间复杂度O(m + n),我们每一次排除一行或者一列。代码如下:
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
class Solution { | |
public: | |
bool searchMatrix(vector<vector<int>>& matrix, int target) { | |
int m = matrix.size(), n = m? matrix[0].size(): 0, i = 0, j = n - 1; | |
while(i < m && j >= 0) | |
{ | |
int curr = matrix[i][j]; | |
if(curr < target)++i; | |
else if(curr > target)--j; | |
else return true; | |
} | |
return false; | |
} | |
}; |
No comments:
Post a Comment