Leetcode solutions 1.4
2 min readMar 29, 2019
657. Robot Return to Origin
class Solution:
def judgeCircle(self, moves: str) -> bool:
end_position = [0, 0]
move_dict = {
'L': [0, -1],
'R': [0, 1],
'U': [1, 0],
'D': [-1, 0]
}
for d in moves:
end_position = [end_position[0] + move_dict[d][0], end_position[1] + move_dict[d][1]]
if end_position == [0, 0]:
return True
else:
return False
905. Sort Array By Parity
def sortArrayByParity(self, A):
"""
:type A: List[int]
:rtype: List[int]
"""
i = 0
j = len(A) - 1
while i < j:
if A[i] % 2 == 0 and A[j] % 2 == 1:
i += 1
j -= 1
elif A[i] % 2 == 1 and A[j] % 2 == 0:
temp = A[j]
A[j] = A[i]
A[i] = temp
i += 1
j -= 1
elif A[i] % 2 == 0 and A[j] % 2 == 0:
i += 1
elif A[i] % 2 == 1 and A[j] % 2 == 1:
j -= 1
return A
942. DI String Match
# Tricky # NOT Heap
def diStringMatch(self, S):
"""
:type S: str
:rtype: List[int]
"""
lo, hi = 0, len(S)
ans = []
for x in S:
if x == "I":
ans.append(lo)
lo += 1
if x == "D":
ans.append(hi)
hi -= 1
ans.append(hi)
return ans
944. Delete Columns to Make Sorted
# Greedy , check if column sorted else add to return list, return the length of unsorted column list
def minDeletionSize(self, A):
"""
:type A: List[str]
:rtype: int
"""
ans = []
rows = len(A)
columns = len(A[0])
for y in range(columns):
column_values = []
isSorted = True
for x in range(rows):
if len(column_values) and A[x][y] < column_values[-1]:
isSorted = False
break
column_values.append(A[x][y])
if isSorted == False:
ans.append(y)
return len(ans)
54. Spiral Matrix
# Faadu code # Really proud of myself :P # The trick is to write very DRY code !
def spiralOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
if not matrix:
return []
dx = 0
dy = 1
xlimit = [0, len(matrix)]
ylimit = [0, len(matrix[0])]
current_loc = (0, 0)
current_value = 1
max_value = xlimit[1] * ylimit[1]
output_array = []
while current_value < max_value:
while current_loc[0] in range(xlimit[0], xlimit[1]) and current_loc[1] in range(ylimit[0], ylimit[1]):
output_array.append(matrix[current_loc[0]][current_loc[1]])
current_value += 1
current_loc = (current_loc[0] + dx, current_loc[1] + dy)
if dy:
if dy < 0:
xlimit[1] -= 1
else:
xlimit[0] += 1
current_loc = (current_loc[0] + dx, current_loc[1] + -1 * dy)
dx = dy
dy = 0
else:
if dx > 0:
ylimit[1] -= 1
else:
ylimit[0] += 1
current_loc = (current_loc[0] + -1 * dx, current_loc[1] + dy)
dy = -dx
dx = 0
current_loc = (current_loc[0] + dx, current_loc[1] + dy)
try:
if matrix[current_loc[0]][current_loc[1]] not in output_array:
output_array.append(matrix[current_loc[0]][current_loc[1]])
except:
pass
return output_array