LeetCode face questions 04. The two-dimensional array lookup to prove safety Offer [] [Easy] [Python] [array]
problem
In a two-dimensional array of n * m, each row from left to right in order of ascending sort, to sort each column from top to bottom in increasing order. A complete function, enter such a two-dimensional array and an integer, it is determined whether the array contains the integer.
Example:
Existing matrix multiplied as follows:
[
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
]
Given target = 5, returns true.
Given target = 20, returns false.
limit:
0 <= n <= 1000
0 <= m <= 1000
NOTE: This problem with the master station 240 issues the same
Thinking
A Solution
violence
直接暴力遍历,遇到相同就返回 True,遍历完所有还没有遇到就返回 False。
Time complexity: O (m * n), where n is the number of matrix rows matrix, m is the number of columns of the matrix matrix.
Space complexity: O (. 1)
Python3 Code
from typing import List
class Solution:
def findNumberIn2DArray(self, matrix: List[List[int]], target: int) -> bool:
# solution one: 暴力
# 特判
if matrix == []:
return False
n, m = len(matrix), len(matrix[0])
for i in range(n):
for j in range(m):
if matrix[i][j] == target:
return True
elif matrix[i][j] > target:
break
return False
Solution two
The lower left corner flag number method
从左下角开始判断
如果相等,就返回;
如果大于 target,就表示该行最小值都要大于 target,所以往上移一行;
如果小于 target,就表示该列最大值都要小于 target,所以往右移一列。
Time complexity: O (n + m), where n is the number of matrix rows matrix, m is the number of columns of the matrix matrix.
Space complexity: O (. 1)
Python3 Code
from typing import List
class Solution:
def findNumberIn2DArray(self, matrix: List[List[int]], target: int) -> bool:
# solution two: 左下角标志数法
i, j = len(matrix) - 1, 0
while i >= 0 and j < len(matrix[0]):
if matrix[i][j] == target:
return True
elif matrix[i][j] > target:
i -= 1
else:
j += 1
return False