티스토리 뷰
알고리즘/HackerRank
[HackerRank] Arrays - (Easy)Left Rotation (왼쪽 회전) javascript 문제 풀이
miiingo 2021. 6. 22. 15:06반응형
■ 문제
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();
}
반응형
'알고리즘 > HackerRank' 카테고리의 다른 글
댓글
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- codility
- 암브로셔스
- 직딩잇템
- 빅데이터
- 빅데이터 기초
- 빅데이터 강의
- docker
- 빅데이터 교육
- ambrosus
- Hyperledger Fabric
- 하이퍼레저 인디
- 기초 of 기초 데이터 개념
- 하이퍼레저 페브릭
- 어서와 데이터는 처음이지
- 코딜리티
- Hyperledger Indy
- 블록체인
- 문제풀이
- javascript
- ubuntu
- 하이퍼레저 패브릭
- 블록 체인
- DOCs
- Blockchain
- Hyperledger Fabric v1.2
- 코테
- Hyperledger Fabric v1.1
- 알고리즘
- Private Data
- 코딩테스트
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 | 31 |
글 보관함