CodeSignal 12. sortByHeight

hjseo-dev·2021년 7월 6일
0

Python 문제풀이

목록 보기
5/7

sortByHeight

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].
  • 배열의 -1을 제외한 수만을 정렬하는 것!
  • 위치와 값을 저장하는 리스트를 따로 만들어서 넣는다. -1의 위치를 넣고, 나머지는 따로 넣어서 정렬한 후 마지막에 해당 위치에 -1을 추가하면 된다.
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

=> 모두 리스트 하나에 넣어서 정렬함

0개의 댓글