Open KevinACoder opened 5 years ago
""" 838. Push Dominoes """
def pushDominoes(D):
max_int = 9999999
#record the distance from current dominoe to nearest push down one(left and right)
left_steps = [max_int for x in range(len(D))]
right_steps = [max_int for x in range(len(D))]
for i in range(len(D)):
if D[i] == 'L':
#if occur one push down domine
left_steps[i] = 0
#for all following domine that influenced
for j in range(i-1, -1, -1):
if D[j] != '.': #only influence '.'
break
left_steps[j] = left_steps[j+1]+1
elif D[i] == 'R':
right_steps[i] = 0
for j in range(i+1, len(D)):
if D[j] != '.':
break
right_steps[j] = right_steps[j-1]+1
#simulate the push work
ND = ''
for i in range(len(D)):
if left_steps[i] < right_steps[i]:
ND += 'L'
elif left_steps[i] > right_steps[i]:
ND += 'R'
else:
ND += '.'
return ND
""" 38. Count and Say """
def say(ns):
ans = ''
s = 0
leng = len(ns)
for e in range(1, leng+1):
if e == leng or ns[s] != ns[e]:
cnt = e - s
ans += str(cnt)
ans += ns[s]
s = e
return ans
def countAndSay(n):
ans = '1'
for _ in range(1, n):
ans = say(ans)
return ans
""" 54. Spiral Matrix """
def spiralOrder(mat):
ans = []
if len(mat) == 0: return ans
#direction of move
dir = 0 # R, D, L, U
#walls of visit [left, right), [up, down)
left = 0
right = len(mat[0]) - 1 #in case of access out of boundary
up = 0
down = len(mat) - 1
num = len(mat)*len(mat[0])
#loop until all mat elements have been put in ans
x = 0
y = 0
#
# ----->
# | |
# <-----
while len(ans) < num:
if dir == 0:
while y < right: #the right most element remained to access in next dir
ans.append(mat[x][y])
y += 1
up += 1
elif dir == 1:
while x < down:
ans.append(mat[x][y])
x += 1
right -= 1
elif dir == 2:
while y > left:
ans.append(mat[x][y])
y -= 1
down -= 1
else:
while x > up:
ans.append(mat[x][y])
x -= 1
right += 1
dir = (dir + 1)%4 #adjust visit direction
#include the central element
return ans
""" if len(ans) != num:
ans.append(mat[x][y]) """
""" 989. Add to Array-Form of Integer """
def addToArrayForm(nums, k):
nums.reverse()
ans = []
for i in range(len(nums)):
k += nums[i]
ans.append(k%10)
k //= 10
while k > 0:
ans.append(k%10)
k //= 10
ans.reverse()
return ans