Code Signal_练习题_Sort by Height

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 def sortByHeight(a):
 2     j = -2
 3     y = 0
 4     li = []
 5     if -1 not in a:
 6         a = sorted(a)
 7     else:
 8         for i in a:
 9             if i == -1:
10                 pass
11             else:
12                 li.append(i)
13                 a[a.index(i)] = j
14                 j -= 1
15         li = sorted(li)
16         for x in a:
17             if x != -1:
18                 a[a.index(x)] = li[y]
19                 y += 1
20     return a

感觉自己总是不按常规出牌

膜拜大佬:

1 def sortByHeight(a):
2 
3     l = sorted([i for i in a if i > 0])
4     for n,i in enumerate(a):
5         if i == -1:
6             l.insert(n,i)
7     return l
View Code

猜你喜欢

转载自www.cnblogs.com/YD2018/p/9351176.html