[GO] [100%] CyclicRotation (src & jUnit)

Painless

CyclicRotation

Rotates the array to the right by the specified number of steps. image.png

Task description

Given an array A of N integers. Rotating the array means that each element is shifted to the right by one index and the last element of the array is moved to the first place. For example, the rotation of array A = [3,8,9,7,6] is [6,3,8,9,7](elements are shifted right by one index, 6 moves to the first place) Will be).

The goal is to rotate the array AK K times. That is, each element of A is shifted to the right K times.

Write a function:

Class Solution {public int [] solution (int [] A, int K);}

Given an array A consisting of N integers and an integer K, it returns an array A rotated K times.

For example, given

A = [3、8、9、7、6]
K = 3

The function should return [9, 7, 6, 3, 8]. Three rotations were made.

[3、8、9、7、6]-> [6、3、8、9、7]
[6、3、8、9、7]-> [7、6、3、8、9]
[7、6、3、8、9]-> [9、7、6、3、8]

As another example

A = [0、0、0]
K = 1

Function must return [0, 0, 0]

Given the

A = [1、2、3、4]
K = 4

Function must return [1, 2, 3, 4]

Suppose:

Your solution will focus on ** correctness **. Solution performance is not the focus of evaluation.


solve

image.png

Program CyclicRotation.java

CyclicRotation.java


    public int[] solution(int[] A, int K) {
        int N = A.length;
        int[] B = new int[N];

        if (N > 0 && K > 0) {
            ArrayList<Integer> arrayB = new ArrayList<Integer>();

            for (int i = 0; i < N; i++) {
                arrayB.add(A[i]);
            }

            for (int j = 0; j < K; j++) {
                arrayB.add(0, arrayB.get(arrayB.size() - 1));
                arrayB.remove(arrayB.size() - 1);
            }

            for (int k = 0; k < arrayB.size(); k++) {
                B[k] = (int) arrayB.get(k);
            }
        } else {
            B = A;
        }

        return B;
    }

junit CyclicRotationTest.java

Report Candidate Report: training6HJBYX-26F


Recommended Posts

[100%] CyclicRotation (src & jUnit)
[100%] PermMissingElem (src & jUnit)
[100%] FrogJmp (src & jUnit)
[100%] FrogRiverOne (src & jUnit)
[100%] OddOccurrencesInArray (src & jUnit)
[100%] MinAvgTwoSlice (src & junit)
[100%] PassingCars (src & junit)
[100%] PermCheck (src & junit)
[100%] TapeEquilibrium (src & jUnit)
[100%] MaxProductOfThree (src & jUnit)
[100%] BinaryGap (src & jUnit)
[100%] MissingInteger (src & junit & author's note)
[100%] [GenomicRangeQuery] (src & junit & author's note)
[100%] MaxCounters (src & junit & author's note)
[100%] Distinct (src & junit & author's note)
[100%] CountDiv (src & junit & author's note)
junit
JUnit 4 notes
JUnit story
JUnit memorandum