본문 바로가기

Algorithms/11 Coding Interview (CS Dojo)

Is One Array a Rotation of Another? (Java)

Write a function that returns true if one array is a rotation of another.

NOTE: There are no duplicates in each of these arrays.

Example: [1, 2, 3, 4, 5, 6, 7] is a rotation of [4, 5, 6, 7, 1, 2, 3].


풀이


import java.util.List;

import java.util.ArrayList;

import java.util.Arrays;


public class IR {

    public static void main(String[] args) {

        // NOTE: The following input values will be used for testing your solution.

        int[] array1 = {1, 2, 3, 4, 5, 6, 7};

        int[] array2a = {4, 5, 6, 7, 8, 1, 2, 3};

        // isRotation(array1, array2a) should return false.

        int[] array2b = {4, 5, 6, 7, 1, 2, 3};

        // isRotation(array1, array2b) should return true.

        int[] array2c = {4, 5, 6, 9, 1, 2, 3};

        // isRotation(array1, array2c) should return false.

        int[] array2d = {4, 6, 5, 7, 1, 2, 3};

        // isRotation(array1, array2d) should return false.

        int[] array2e = {4, 5, 6, 7, 0, 2, 3};

        // isRotation(array1, array2e) should return false.

        int[] array2f = {1, 2, 3, 4, 5, 6, 7};

        // isRotation(array1, array2f) should return true.

    }


    // Implement your solution below.

    public static Boolean isRotation(int[] array1, int[] array2) {

        boolean result = false;

        if (array1.length != array2.length)

            return result;

        List<Integer> array2List = new ArrayList<>();

        for (int i : array2) {

            array2List.add(i);

        }

        int size = array2List.size();

        int index1 = array2List.indexOf(array1[0]);

        if (index1 == -1)

            return result;

        int interval = array2List.size() - index1;

        for (int i = index1; i < size; i++) {

            array2List.remove(index1);

        }

        for (int i = 0; i < interval; i++) {

            array2List.add(i, i+1);

        }

        int[] newArray2 = new int[size];

        for (int i = 0; i<array2List.size(); i++){

            newArray2[i] = array2List.get(i);

        }

        if (!Arrays.toString(array1).equals(Arrays.toString(newArray2))){

            result = false;

            return result;

        } else {

            result = true;

            return result;

        }

    }

}