Skip to content

Commit 463c34d

Browse files
committed
Create search-a-2d-matrix-ii.py
1 parent 9ad5672 commit 463c34d

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

Python/search-a-2d-matrix-ii.py

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
# Time: O(m + n)
2+
# Space: O(1)
3+
#
4+
# Write an efficient algorithm that searches for a value in an m x n matrix.
5+
# This matrix has the following properties:
6+
#
7+
# Integers in each row are sorted in ascending from left to right.
8+
# Integers in each column are sorted in ascending from top to bottom.
9+
# For example,
10+
#
11+
# Consider the following matrix:
12+
#
13+
# [
14+
# [1, 4, 7, 11, 15],
15+
# [2, 5, 8, 12, 19],
16+
# [3, 6, 9, 16, 22],
17+
# [10, 13, 14, 17, 24],
18+
# [18, 21, 23, 26, 30]
19+
# ]
20+
# Given target = 5, return true.
21+
#
22+
# Given target = 20, return false.
23+
#
24+
25+
class Solution:
26+
# @param {integer[][]} matrix
27+
# @param {integer} target
28+
# @return {boolean}
29+
def searchMatrix(self, matrix, target):
30+
m = len(matrix)
31+
if m == 0:
32+
return False
33+
34+
n = len(matrix[0])
35+
if n == 0:
36+
return False
37+
38+
count, i, j = 0, 0, n - 1
39+
while i < m and j >= 0:
40+
if matrix[i][j] == target:
41+
return True
42+
elif matrix[i][j] > target:
43+
j -= 1
44+
else:
45+
i += 1
46+
47+
return False

0 commit comments

Comments
 (0)