Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions Problem3-Leetcode54.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
#Time Complexity: O(m*n)
#Space Complexity: O(1)

class Solution(object):
def spiralOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
result = []
if not matrix:
return result

top, bottom = 0, len(matrix) - 1
left, right = 0, len(matrix[0]) - 1

while top <= bottom and left <= right:
for i in range(left, right + 1):
result.append(matrix[top][i])
top += 1

for i in range(top, bottom + 1):
result.append(matrix[i][right])
right -= 1

if top <= bottom:
for i in range(right, left - 1, -1):
result.append(matrix[bottom][i])
bottom -= 1

if left <= right:
for i in range(bottom, top - 1, -1):
result.append(matrix[i][left])
left += 1

return result
24 changes: 24 additions & 0 deletions problem1-leetcode238.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
#Time Complexity: O(n)
#Space Complexity: O(n)

class Solution(object):
def productExceptSelf(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
n, runningProduct = len(nums), 1
leftProduct = [0] * n
leftProduct[0] = 1

for i in range(1, len(nums)):
runningProduct = runningProduct * nums[i - 1]
leftProduct[i] = runningProduct

runningProduct = 1
for i in range(n-2, -1, -1):
runningProduct = runningProduct * nums[i + 1]
leftProduct[i] = leftProduct[i] * runningProduct

return leftProduct

37 changes: 37 additions & 0 deletions problem2-Leetcode498.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
#Time Complexity: O(m*n)
#Space Complexity: O(1)

class Solution(object):
def findDiagonalOrder(self, mat):
"""
:type mat: List[List[int]]
:rtype: List[int]
"""
m, n = len(mat), len(mat[0])
r, c, x, flag = 0, 0, m * n, True
arr = []
for _ in range(x):
arr.append(mat[r][c])
if flag:
if r == 0 and c != n - 1:
c += 1
flag = False
elif c == n - 1:
r += 1
flag = False
else:
r -= 1
c += 1
else:
if c == 0 and r != m - 1:
r += 1
flag = True
elif r == m - 1:
c += 1
flag = True
else:
r += 1
c -= 1

return arr