Some people are standing in a row in a park. There are trees between them which cannot be moved. Your task is to rearrange the people by their heights in a non-descending order without moving the trees. People can be very tall!
Example
For a = [-1, 150, 190, 170, -1, -1, 160, 180],
the output should be
sortByHeight(a) = [-1, 150, 160, 170, -1, -1, 180, 190].
def sortByHeight(a):
arr = [] # 위치저장
arr_b=[] # 값저장
for i in range(len(a)):
if a[i] == -1:
arr.append(i)
else:
arr_b.append(a[i])
arr_b.sort()
for j in arr: #해당 값에 -1 넣기
arr_b.insert(j,-1)
return arr_b
최적화된 풀이
def sortByHeight(a):
l = sorted([i for i in a if i > 0])
for n,i in enumerate(a):
if i == -1:
l.insert(n,i)
return l
=> 모두 리스트 하나에 넣어서 정렬함