题目
代码
执行用时:32 ms, 在所有 Python3 提交中击败了92.15% 的用户
内存消耗:19.1 MB, 在所有 Python3 提交中击败了27.07% 的用户
通过测试用例:129 / 129
class Solution:
def findNumberIn2DArray(self, matrix: List[List[int]], target: int) -> bool:
ans=False
for line in matrix:
if target in line:
ans=True
return ans
【方法2】
执行用时:56 ms, 在所有 Python3 提交中击败了8.25% 的用户
内存消耗:19.1 MB, 在所有 Python3 提交中击败了38.90% 的用户
通过测试用例:129 / 129
class Solution:
def findNumberIn2DArray(self, matrix: List[List[int]], target: int) -> bool:
ans=False
for line in matrix:
cnt=Counter(line)
if target in cnt:
ans=True
return ans
【方法3】
执行用时:36 ms, 在所有 Python3 提交中击败了78.50% 的用户
内存消耗:19.2 MB, 在所有 Python3 提交中击败了17.49% 的用户
通过测试用例:129 / 129
class Solution:
def findNumberIn2DArray(self, matrix: List[List[int]], target: int) -> bool:
i, j = len(matrix) - 1, 0
while i >= 0 and j < len(matrix[0]):
if matrix[i][j] > target: i -= 1
elif matrix[i][j] < target: j += 1
else: return True
return False
【方法4】
执行用时:40 ms, 在所有 Python3 提交中击败了57.17% 的用户
内存消耗:19.1 MB, 在所有 Python3 提交中击败了35.09% 的用户
通过测试用例:129 / 129
class Solution:
def findNumberIn2DArray(self, matrix: List[List[int]], target: int) -> bool:
x,y=len(matrix)-1,0
while x>=0 and y<len(matrix[0]):
if matrix[x][y]<target:
y+=1
elif matrix[x][y]>target:
x-=1
elif matrix[x][y]==target:
return True
return False