chapter 1 sorted matrix search v1

This commit is contained in:
anebz 2019-04-08 22:38:16 +02:00
parent f04e89c4f8
commit d520f7c64d
3 changed files with 93 additions and 1 deletions

View File

@ -0,0 +1,44 @@
# 10.9. Sorted matrix search
## Given an M x N matrix in which each row and each column is sorted in ascending order, write a method to find an element
> example
```python
A = [[1,2,4,5,7],
[2,3,5,6,8],
[3,6,7,8,10],
[4,7,8,9,11]]
num = 3
```
## First idea
If A[0][3] < num and A[3][0] < num, if A[3][3] < num, return -1. Otherwise it must be in the matrix.
If A[0][3] => num or A[3][0] => num, Iterate through the last column, find first row where `A[row][3] > num`. Then iterate that row from the back. If not found, iterate through the last row, do the same. This should take O(N+M) in the worst case.
```python
def search_sorted_matrix(M, N, A, num):
if num < A[0][0] or num > A[M][N]:
return 0
if num == A[0][0] or num == A[M][N]:
return 1
if num < A[0][N]:
initidx = 0
maxidx = N
while True:
i = maxidx // 2
if A[0][i] == num:
return 1
elif A[0][i] > num:
maxidx = i
elif A[0][i] < num:
initidx = i
if A[0][initidx] < num and A[0][initidx+1] > num:
break
```

View File

@ -0,0 +1,44 @@
import unittest
M = 5 - 1
N = 5 - 1
def search_sorted_matrix(A, num):
if num < A[0][0] or num > A[M][N]:
return 0
if num == A[0][0] or num == A[M][N]:
return 1
if num < A[0][N]:
initidx = 0
maxidx = N
while True:
i = maxidx // 2
if A[0][i] == num:
return 1
elif A[0][i] > num:
maxidx = i
elif A[0][i] < num:
initidx = i
if A[0][initidx] < num and A[0][initidx+1] > num:
break
return 0
class Test(unittest.TestCase):
data = [
([
[0, 1, 3, 4, 6],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20],
[21, 22, 23, 24, 25]
], 2, 1)
]
def test_rotate_matrix(self):
for test_matrix, num, expected in self.data:
actual = search_sorted_matrix(test_matrix, num)
self.assertEqual(actual, expected)
if __name__ == "__main__":
unittest.main()

View File

@ -24,3 +24,7 @@
## Chapter 8 Recursion
* Magic index
## Chapter 10 Sorting and searching
* Sorted matrix search