原题连接:https://www.acwing.com/problem/content/16/
/*
参考题解:https://www.acwing.com/solution/content/702/
时间复杂度O(n+m) 本来是O(n*m)的
*/
class Solution {
public:
bool searchArray(vector<vector<int>> array, int target) {
if(array.empty() || array[0].empty()) return false;
int i = 0, j = array[0].size() - 1;
while(j >= 0 && i <= array.size() - 1)
{
if(array[i][j] == target) return true;
if(array[i][j] > target) j --;
else i ++;
}
return false;
}
};
class Solution(object):
def searchArray(self, array, target):
"""
:type array: List[List[int]]
:type target: int
:rtype: bool
"""
# 若为空直接返回
if len(array) == 0 or len(array[0]) == 0:
return False
# 从右上角往左下角进行遍历
i, j = 0, len(array[0]) - 1
while i <= len(array) - 1 and j >= 0:
if array[i][j] == target:
return True
if array[i][j] > target:
j = j - 1
else:
i = i + 1
return False