Given an array of n distinct integers, transform the array into a zig zag sequence by permuting the array elements. A sequence will be called a zig zag sequence if the first k elements in the sequence are in increasing order and the last k elements are in decreasing order, where k=(n+1)/2. You need to find the lexicographically smallest zig zag sequence of the given array.
Example.
a [2, 3, 5, 1, 4]
Now if we permute the array as [1, 4, 5, 3, 2], the result is a zig zag sequence.
Debug the given function findZigZagSequence to return the appropriate zig zag sequence for the given input array.
Note: You can modify at most three lines in the given code. You cannot add or remove lines of code.
To restore the original code, click on the icon to the right of the language selector.
Input Format
The first line contains t the number of test cases. The first line of each test case contains an integer n, denoting the number of array elements. The next line of the test case contains n elements of array a.
Constraints
1 <= t <= 20
1 <= n <= 10000(n is always odd)
1 <= a_i <= 10^9
Output Format
For each test cases, print the elements of the transformed zig zag sequence in a single line.
def findZigZagSequence(a, n):
a.sort()
mid = int(n/2) # 수정 (1)
a[mid], a[n-1] = a[n-1], a[mid]
st = mid + 1
ed = n - 2 # 수정 (2)
while(st <= ed):
a[st], a[ed] = a[ed], a[st]
st = st + 1
ed = ed - 1 # 수정 (3)
for i in range (n):
if i == n-1:
print(a[i])
else:
print(a[i], end = ' ')
return
이 문제는 구현해서 푸는 문제가 아니라 문제를 디버깅하여 수정하는 문제다.
이런 유형의 문제는 처음이라 조금 당황했었다.
전 날 고민하다가 도저히 안 풀려서 오늘 아침에 다시 풀었는데. 아주 굿! 잘 풀렸다.
문제가 안 풀리면 잠시 쉬고 푸는 것도 좋은 선택이다.
'알고리즘 > HackerRank' 카테고리의 다른 글
[HackerRank] Counting Sort 1 (2) | 2023.06.13 |
---|---|
[HackerRank] Diagonal Difference (0) | 2023.06.13 |
[HackerRank] Lonely Integer (0) | 2023.06.13 |
[HackerRank] Time Conversion (endswitch, zfill 메소드/테스트 케이스) (0) | 2023.06.12 |
[HackerRank] Mini-Max Sum (0) | 2023.06.12 |