Coding Test/HackerRank

[HackerRank] Zig Zag Sequence C++

owls 2022. 7. 20. 14:54
728x90
  • Problem

In this challenge, the task is to debug the existing code to successfully execute all provided test files.


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,3]

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.

  • Constraints

1 <= t <= 20

1 <= n <= 10000(n is always odd)

1 <= a[i] <= 10^9

  • Solutions

이번 문제는 주어진 코드에서 틀린 코드를 수정하는 문제이다.

3개 라인을 수정해야한다.

sample example이 없어서 문제 해석이 헷갈렸다.

오름차순으로 정렬 후 가운데 index를 기준으로 배열의 요소를 지그재그로 변경하라고 이해했는데 이건 아닌거같다.

 

프로그램 검사를 line 번째로 하드코딩해놓은거 같다.

주석처리하고 다음 line에 추가 삽입했더니 error가 났다.

void findZigZagSequence(vector < int > a, int n){
    sort(a.begin(), a.end());
    int mid = (n)/2; //int mid = (n + 1)/2; 수정1
    swap(a[mid], a[n-1]);

    int st = mid + 1;                          // 가운데 index로 변경
    int ed = n - 2;  //int ed = n - 1; 수정2    //가운데 index로 변경
    while(st <= ed){
        swap(a[st], a[ed]);
        st = st + 1;
        ed = ed - 1; //ed = ed + 1; 수정3
    }
    for(int i = 0; i < n; i++){
        if(i > 0) cout << " ";
        cout << a[i];
    }
    cout << endl;
}

hackerrank zig zag sequence c++

 

728x90