Skip to content

Commit 777337b

Browse files
author
wuduhren
committed
updates
1 parent 66f6f8d commit 777337b

File tree

3 files changed

+83
-0
lines changed

3 files changed

+83
-0
lines changed

problems/python3/binary-search.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
class Solution:
2+
def search(self, nums: List[int], target: int) -> int:
3+
l = 0
4+
r = len(nums)-1
5+
6+
while l<=r:
7+
m = l + int((r-l)/2)
8+
9+
if nums[m]>target:
10+
r = m-1
11+
elif nums[m]<target:
12+
l = m+1
13+
else:
14+
return m
15+
16+
return -1

problems/python3/n-queens.py

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
class Solution:
2+
def solveNQueens(self, n: int) -> List[List[str]]:
3+
def helper(row: int):
4+
if row==n:
5+
ans.append(convertFormat(queenCols))
6+
return
7+
8+
for col in range(n):
9+
posDiag = row+col
10+
negDiag = row-col
11+
12+
if col in colUsed or posDiag in posDiagUsed or negDiag in negDiagUsed: continue
13+
14+
queenCols.append(col)
15+
colUsed.add(col)
16+
posDiagUsed.add(posDiag)
17+
negDiagUsed.add(negDiag)
18+
19+
helper(row+1)
20+
21+
queenCols.pop()
22+
colUsed.remove(col)
23+
posDiagUsed.remove(posDiag)
24+
negDiagUsed.remove(negDiag)
25+
26+
def convertFormat(queenCols: List[int]) -> List[str]:
27+
output = []
28+
for col in queenCols:
29+
row = ''
30+
for i in range(n):
31+
if i==col:
32+
row += 'Q'
33+
else:
34+
row += '.'
35+
output.append(row)
36+
return output
37+
38+
ans = []
39+
queenCols = []
40+
colUsed = set()
41+
posDiagUsed = set()
42+
negDiagUsed = set()
43+
44+
helper(0)
45+
return ans
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
class Solution:
2+
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
3+
N = len(matrix)
4+
M = len(matrix[0])
5+
6+
l = 0
7+
r = N*M-1
8+
9+
while l<=r:
10+
m = l + int((r-l)/2)
11+
12+
i = int(m/M)
13+
j = m%M
14+
15+
if matrix[i][j]<target:
16+
l = m+1
17+
elif matrix[i][j]>target:
18+
r = m-1
19+
else:
20+
return True
21+
22+
return False

0 commit comments

Comments
 (0)