티스토리 뷰

Input Format

첫줄에 n k (integer 의 개수, 왼쪽으로 이동시킬 개수), 둘째줄에 space 로 분리된 n개의 int타입 element 를 입력 

The first line contains two space-separated integers denoting the respective values of  (the number of integers) and  (the number of left rotations you must perform). 
The second line contains  space-separated integers describing the respective elements of the array's initial state.

Constraints

Output Format

한줄에 n개의 space 로분리된 integer 을  프린트한다. 프린트되는 값은 입력된 n개의 array 값을왼쪽으로 k 번 이동했을때의 값이다.

Print a single line of  space-separated integers denoting the final state of the array after performing  left rotations.

Sample Input

5 4
1 2 3 4 5

Sample Output

5 1 2 3 4


Solution

import java.text.*; import java.math.*; import java.util.regex.*; public class Solutin { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int k = in.nextInt(); int a[] = new int[n]; for(int a_i=0; a_i < n; a_i++){ a[a_i] = in.nextInt(); } //배열을 만들지 않고, 프린트만 하면 된다. for(int i=0;i<n;i++){ int move= (i+k)%n; if(i==0){ System.out.print(a[move]); }else{ System.out.print(" "+a[move]); } } } }



초반에 roateArray 라는 함수를 만들어서, n, k, array 값을 받은 다음 

resultArray 라는 rotate 완료된 배열을 생성하여 그 배열을프린트하려고 했다.


배열을 이동시켜 새로운 배열을 반들기 위해 processing 하는데 시간이 많이 들어 Test case 에서 Time out 되어버렸다 ㅜㅜ 


다시 문제를 잘 읽어보니 배열을 만들 필요는 없고 프린트만 하면 되기때문에 move 변수를 계산하여 화살표? 처럼 사용했다


원하는 output 값이 1 2 3 처럼 서로 띄어쓰기를 하여 구분한 String 인데, 그걸위해 i=0일때와 아닐때 구분하는건 비효율적인것같다 ..더좋은방법이 있을듯



출처 : https://www.hackerrank.com/challenges/ctci-array-left-rotation/problem

'Programming' 카테고리의 다른 글

[Java] 문자열  (0) 2018.03.30
[Java 문제풀이] String - Anagram  (0) 2018.03.16
[Java 문제풀이] - 피보나치  (0) 2018.03.10
[Python] 파이썬 문법  (0) 2018.03.03
OOP 객체지향 프로그래밍  (0) 2017.12.12
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2025/03   »
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
글 보관함