diff --git a/diagonalTraverse.py b/diagonalTraverse.py new file mode 100644 index 00000000..f2c29469 --- /dev/null +++ b/diagonalTraverse.py @@ -0,0 +1,40 @@ +# // Time Complexity : O(m*n) +# // Space Complexity : O(1) +# // Did this code successfully run on Leetcode : Yes + +class Solution(object): + def findDiagonalOrder(self, mat): + """ + :type mat: List[List[int]] + :rtype: List[int] + """ + m=len(mat) + n=len(mat[0]) + reslen=m*n + res=[] + dir=1 + r,c=0,0 + for i in range(reslen): + res.append(mat[r][c]) + if (dir): + if (c==n-1): + r+=1 + dir=0 + elif (r==0): + c+=1 + dir=0 + else: + r-=1 + c+=1 + else: + if (r==m-1): + c+=1 + dir=1 + elif (c==0): + r+=1 + dir=1 + else: + r+=1 + c-=1 + + return res diff --git a/productExceptSelf.py b/productExceptSelf.py new file mode 100644 index 00000000..98fe61c4 --- /dev/null +++ b/productExceptSelf.py @@ -0,0 +1,22 @@ +# // Time Complexity : O(n) +# // Space Complexity : O(1) +# // Did this code successfully run on Leetcode : Yes + +class Solution(object): + def productExceptSelf(self, nums): + """ + :type nums: List[int] + :rtype: List[int] + """ + lprod=[1] + rp=1 + n=len(nums) + for i in range(1,n): + rp=nums[i-1]*rp + lprod.append(rp) + rp=1 + for i in range(n-2,-1,-1): + rp=nums[i+1]*rp + lprod[i]*=rp + + return lprod diff --git a/sprialMatrix.py b/sprialMatrix.py new file mode 100644 index 00000000..a7c0d1c5 --- /dev/null +++ b/sprialMatrix.py @@ -0,0 +1,37 @@ +# // Time Complexity : O(m*n) +# // Space Complexity : O(1) +# // Did this code successfully run on Leetcode : Yes + +class Solution(object): + def spiralOrder(self, matrix): + """ + :type matrix: List[List[int]] + :rtype: List[int] + """ + rows= len(matrix) + cols=len(matrix[0]) + top=0 + left=0 + right=cols-1 + bottom=rows-1 + res=[] + + while top<=bottom and left<=right: + # L to R + for c in range(left,right+1): + res.append(matrix[top][c]) + top+=1 + #T to B + for r in range(top,bottom+1): + res.append(matrix[r][right]) + right-=1 + if top<=bottom: + for c in range(right,left-1,-1): + res.append(matrix[bottom][c]) + bottom-=1 + if left<=right: + for r in range(bottom,top-1,-1): + res.append(matrix[r][left]) + left+=1 + + return res