Skip to content

Commit 3cccb2a

Browse files
committed
Sync LeetCode submission Runtime - 70 ms (5.65%), Memory - 14.8 MB (100.00%)
1 parent f7e9fc4 commit 3cccb2a

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed

0074-search-a-2d-matrix/README.md

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
<p>You are given an <code>m x n</code> integer matrix <code>matrix</code> with the following two properties:</p>
2+
3+
<ul>
4+
<li>Each row is sorted in non-decreasing order.</li>
5+
<li>The first integer of each row is greater than the last integer of the previous row.</li>
6+
</ul>
7+
8+
<p>Given an integer <code>target</code>, return <code>true</code> <em>if</em> <code>target</code> <em>is in</em> <code>matrix</code> <em>or</em> <code>false</code> <em>otherwise</em>.</p>
9+
10+
<p>You must write a solution in <code>O(log(m * n))</code> time complexity.</p>
11+
12+
<p>&nbsp;</p>
13+
<p><strong class="example">Example 1:</strong></p>
14+
<img alt="" src="https://assets.leetcode.com/uploads/2020/10/05/mat.jpg" style="width: 322px; height: 242px;" />
15+
<pre>
16+
<strong>Input:</strong> matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
17+
<strong>Output:</strong> true
18+
</pre>
19+
20+
<p><strong class="example">Example 2:</strong></p>
21+
<img alt="" src="https://assets.leetcode.com/uploads/2020/10/05/mat2.jpg" style="width: 322px; height: 242px;" />
22+
<pre>
23+
<strong>Input:</strong> matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13
24+
<strong>Output:</strong> false
25+
</pre>
26+
27+
<p>&nbsp;</p>
28+
<p><strong>Constraints:</strong></p>
29+
30+
<ul>
31+
<li><code>m == matrix.length</code></li>
32+
<li><code>n == matrix[i].length</code></li>
33+
<li><code>1 &lt;= m, n &lt;= 100</code></li>
34+
<li><code>-10<sup>4</sup> &lt;= matrix[i][j], target &lt;= 10<sup>4</sup></code></li>
35+
</ul>

0074-search-a-2d-matrix/solution.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# Approach 1 - Binary Search
2+
3+
# Time: O(log(mn)), Space: O(1)
4+
5+
class Solution:
6+
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
7+
if not matrix:
8+
return False
9+
10+
m = len(matrix)
11+
n = len(matrix[0])
12+
13+
left, right = 0, m * n - 1
14+
15+
while left <= right:
16+
pivot_idx = left + (right - left) // 2
17+
pivot_element = matrix[pivot_idx // n][pivot_idx % n]
18+
19+
if target == pivot_element:
20+
return True
21+
elif target < pivot_element:
22+
right = pivot_idx - 1
23+
else:
24+
left = pivot_idx + 1
25+
26+
return False

0 commit comments

Comments
 (0)