티스토리 뷰

Codesignal

code signal - 12. Sort by Height

터보건 2020. 1. 29. 16:51

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 be sortByHeight(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 the ith position is occupied by a tree. Otherwise a[i] is the height of a person standing in the ith position.

    Guaranteed constraints: 1 ≤ a.length ≤ 1000, -1 ≤ a[i] ≤ 1000.

  • [output] array.integer

    • Sorted array a with all the trees untouched.

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의 경우 하나의 리스트에서 한 번에 처리하였다.

'Codesignal' 카테고리의 다른 글

code signal - 14. alternatingSums  (0) 2020.02.10
code signal - 13. reverseInParentheses  (0) 2020.02.09
code signal - 11. isLucky  (0) 2020.01.29
code signal - 10. commonCharacterCount  (0) 2020.01.29
code signal - 9. All Longest Strings  (0) 2020.01.29
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/11   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
글 보관함