Question
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 besortByHeight(a) = [-1, 150, 160, 170, -1, -1, 180, 190]
.
Input/Output
[execution time limit] 4 seconds (py3)
[input] array.integer a
If
a[i] = -1
, then theith
position is occupied by a tree. Otherwisea[i]
is the height of a person standing in theith
position.Guaranteed constraints:
1 ≤ a.length ≤ 1000
,-1 ≤ a[i] ≤ 1000
.[output] array.integer
- Sorted array
a
with all the trees untouched.
- Sorted array
MY_ANSWER
def sortByHeight(a):
tree = []
person = []
for i in range(len(a)):
if a[i] == -1:
tree.append(i)
else:
person.append(a[i])
person.sort()
for j in tree:
person.insert(j,-1)
return person
-> 나무의 위치를 인덱스로 받고, 정렬된 사람 사이에 위치에 따라 나무를 집어 넣는다.
Best_ANSWER
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
-> 나의 코드가 나무 위치, 사람에 대한 정보를 따로따로 받았다면, best_answer의 경우 하나의 리스트에서 한 번에 처리하였다.