Rotate String by Left

2018-04-16  本文已影响0人  Star_C

Questions

Hackerank
Rotate a string of n characters by k steps.

Idea

Index Addition

A position + X steps has a total length of X + 1

Circular Moves

Using % length to retrieve actual steps without meaningless step repetition

Backward Move

Think of a circle.
Array.length is conceptually the same position as index 0. If you move left from position 0, you are actually moving left from position Array.length.

    public static void rotate(int[] a, int K) {
        int[] tmp = new int[a.length];
        int target = 0;
        int k = K % a.length;
        for(int i = 0; i < a.length; i++) {
            target = i < k?
                      a.length - (k - i):
                      i - k;
            tmp[target] = a[i];
        }
        for(int i = 0; i < a.length; i++) {
            a[i] = tmp[i];
        }
    }
上一篇下一篇

猜你喜欢

热点阅读