新农上路
- 积分
- 92
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2015-7-27
- 最后登录
- 1970-1-1
|
Python version:
#!/usr/bin/env python
import random
class Solution:
def genSawArray(self, input):
if len(input) < 3:
return input
output = list(input)
for index, value in enumerate(output):
if not index % 2:
continue
# odd index is not in the end
if index != len(output) - 1:
tmp_arr = [output[index - 1], output[index], output[index + 1]]
output[index] = max(tmp_arr)
output[index - 1] = min(tmp_arr)
output[index + 1] = sum(tmp_arr) - output[index - 1] - output[index + 1]
# odd index is in the end
else:
output[index - 1] = min(output[index - 1], output[index])
output[index] = max(output[index - 1], output[index])
print output
if __name__ == "__main__":
arr = random.sample(range(30), random.randint(7, 15))
print arr
solution = Solution()
solution.genSawArray(arr)
Test:
enzo@enzo-ubuntu:~/Documents/code/todel$ python wigglesort.py
[26, 24, 7, 22, 14, 8, 2, 11]
[7, 26, 14, 43, 2, 51, 11, 11]
enzo@enzo-ubuntu:~/Documents/code/todel$ python wigglesort.py
[13, 11, 8, 1, 3, 16, 18, 19, 23, 27, 22, 24, 12, 26, 0]
[8, 13, 1, 16, 16, 18, 16, 23, 19, 27, 12, 27, 0, 39, 65]
enzo@enzo-ubuntu:~/Documents/code/todel$ python wigglesort.py
[2, 13, 26, 12, 29, 19, 5, 23, 18]
[2, 26, 12, 29, 5, 19, 18, 27, 32]
|
|