티스토리 뷰

반응형

■ 문제

원본 사이트: https://www.hackerrank.com/challenges/ctci-array-left-rotation/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=arrays 

 

Arrays: Left Rotation | HackerRank

Given an array and a number, d, perform d left rotations on the array.

www.hackerrank.com

 

난이도: Easy

최대 스코어: 20

 

● 문제 요약

  • Left Rotation(왼쪽 회전): 배열의 각 요소를 왼쪽으로 1칸씩 이동한 것
  • n 개의 정수로 구성된 배열 a와 숫자 d가 주어짐
  • 배열 a에서 d 번의 왼쪽 회전을 수행한 뒤, 업데이트된 배열 a를 공백으로 구분된 한 줄의 정수로 return

 

예시:

a = [1, 2, 3, 4, 5]
d = 4
  • d = 1  -->  [2, 3, 4, 5, 1]
  • d = 2  -->  [3, 4, 5, 1, 2]
  • d = 3  -->  [4, 5, 1, 2, 3]
  • d = 4  -->  [5, 1, 2, 3, 4]

==> return 5 1 2 3 4

 

 

■ 문제 풀이

배열의 길이만큼 회전하면 다시 원래의 배열 상태로 돌아오게 된다.

그렇기 때문에 d 번의 왼쪽 회전을 모두 수행할 필요 없이, d에서 배열 a의 길이만큼 나눈 것의 나머지 값만큼만 왼쪽 회전을 수행하면 된다.

한 칸씩 왼쪽으로 밀리는 것이기 때문에 배열의 순서에는 변함이 없으므로, 왼쪽 회전을 수행해야하는 횟수만큼 배열을 잘라서 뒤에 붙이면 된다.

 

● 완성 코드 - 20 Points (Max)

'use strict';

const fs = require('fs');

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', function() {
    inputString = inputString.replace(/\s*$/, '')
        .split('\n')
        .map(str => str.replace(/\s*$/, ''));

    main();
});

function readLine() {
    return inputString[currentLine++];
}

// Complete the rotLeft function below.
function rotLeft(a, d) {
    const rotCnt = d % a.length;
    const rotArr = a.splice(0, rotCnt);
    return a.concat(rotArr);
}

function main() {
    const ws = fs.createWriteStream(process.env.OUTPUT_PATH);

    const nd = readLine().split(' ');

    const n = parseInt(nd[0], 10);

    const d = parseInt(nd[1], 10);

    const a = readLine().split(' ').map(aTemp => parseInt(aTemp, 10));

    const result = rotLeft(a, d);

    ws.write(result.join(' ') + '\n');

    ws.end();
}
반응형
댓글
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함