[英]Python Code Not Working!-- Convert array into Zig-Zag fashion
Given an array arr of distinct elements of size N, the task is to rearrange the elements of the array in a zig-zag fashion so that the converted array should be in the below form: arr[0] < arr[1] > arr[2] < arr[3] > arr[4] <.给定一个大小为 N 的不同元素的数组 arr,任务是以之字形方式重新排列数组的元素,以便转换后的数组应为以下形式: arr[0] < arr[1] > arr [2]<arr[3]>arr[4]<. . . . . . . arr[n-2] < arr[n-1] > arr[n]. arr[n-2] < arr[n-1] > arr[n]。
def zigZag(self,arr, n):
res=[]
r=(n//2)+1
arr.sort()
j=0
i=0
for k in range(0, r, 1):
res.insert(i, arr[j])
res.insert(i+1, arr[j+r])
i= i+2
j+= j
return res
You can sort the array and add to the new array from both sides of the array.您可以对数组进行排序并从数组的两侧添加到新数组中。
def zigZag(self, arr, n):
res=[None]*n
arr.sort()
i = 0
j = 0
while i < n//2:
res[j] = arr[i]
res[j+1] = arr[n-1-i]
i+=1
j+=2
if n%2 == 1:
res[-1] = arr[n//2]
return res
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.