Java/Algorithm

[Java-Algorithm] HackerRank Java Arrays: Left Rotation 풀이

Jeong Jeon
반응형

1). 문제 : www.hackerrank.com/challenges/ctci-array-left-rotation

 

Arrays: Left Rotation | HackerRank

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

www.hackerrank.com

 

2). 풀이 :

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;

public class Solution {

    // Complete the rotLeft function below.
    static int[] rotLeft(int[] a, int d) {
        int[] result =a;
        
        for(int i=0; i<d; i++){
            int temp = a[0];//뒤로 붙일값 저장
            for(int k=0; k<result.length-1; k++){
                result[k] = result[k+1]; //한칸씩 앞으로=> 앞으로 해야될 갯수만큼
            }
            result[result.length-1]=temp;
            
        }
        return result;
    }

    private static final Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) throws IOException {
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

        String[] nd = scanner.nextLine().split(" ");

        int n = Integer.parseInt(nd[0]);

        int d = Integer.parseInt(nd[1]);

        int[] a = new int[n];

        String[] aItems = scanner.nextLine().split(" ");
        scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

        for (int i = 0; i < n; i++) {
            int aItem = Integer.parseInt(aItems[i]);
            a[i] = aItem;
        }

        int[] result = rotLeft(a, d);

        for (int i = 0; i < result.length; i++) {
            bufferedWriter.write(String.valueOf(result[i]));

            if (i != result.length - 1) {
                bufferedWriter.write(" ");
            }
        }

        bufferedWriter.newLine();

        bufferedWriter.close();

        scanner.close();
    }
}

 

반응형