Skip to content

Commit 89455fc

Browse files
Chris WuChris Wu
Chris Wu
authored and
Chris Wu
committed
no message
1 parent 737c345 commit 89455fc

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
class Solution(object):
2+
def kthSmallest(self, matrix, k):
3+
memo = [0]*len(matrix)
4+
opt = []
5+
while len(opt)<k:
6+
m = float('inf')
7+
i_min = None
8+
for i, row in enumerate(matrix):
9+
if memo[i]<len(matrix) and row[memo[i]]<m:
10+
m = row[memo[i]]
11+
i_min = i
12+
opt.append(m)
13+
memo[i_min]+=1
14+
return opt[-1]

problems/search-a-2d-matrix.py

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
"""
2+
First I decided to flatten the matrix to an 1-D array, `A`.
3+
Because it is easier to navigate in this structure.
4+
And because `A` is already sorted, we can aplly binary search here.
5+
"""
6+
class Solution(object):
7+
def searchMatrix(self, matrix, target):
8+
A = []
9+
for row in matrix: A.extend(row)
10+
11+
l = 0
12+
r = len(A)-1
13+
while l<=r:
14+
m = (l+r)/2
15+
if A[l]==target: return True
16+
if A[m]==target: return True
17+
if A[r]==target: return True
18+
19+
if A[m]>target:
20+
r = m-1
21+
else:
22+
l = m+1
23+
return False
24+
25+
class Solution(object):
26+
def searchMatrix(self, matrix, target):
27+
def getMatrix(i):
28+
n = i/M
29+
m = i%M
30+
return matrix[n][m]
31+
32+
if not matrix or len(matrix)==0 or len(matrix[0])==0: return False
33+
34+
N = len(matrix)
35+
M = len(matrix[0])
36+
37+
l = 0
38+
r = N*M-1
39+
while l<=r:
40+
p = (l+r)/2
41+
if getMatrix(l)==target: return True
42+
if getMatrix(p)==target: return True
43+
if getMatrix(r)==target: return True
44+
45+
if getMatrix(p)>target:
46+
r = p-1
47+
else:
48+
l = p+1
49+
return False

0 commit comments

Comments
 (0)