My 0ms Java

  • 0

    Rotate an array of n elements to the right by k steps.
    For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].

    Here I calculated a modular to represent the direct displacements of each element in the array. Instead to move every element one by one, we can separate them into 2 clusters based on the modular.

    For example:

    For array [1,2,3,4,5,6,7], when k is 3, we could get a modular as 3, because 3 % 7 = 3. Then we separate the array into two clusters: one is [1,2,3,4] and the other is [5,6,7]. Next, we just need to reform/exchange the sequences of these 2 clusters, and the problem will be solved.

    To exchange the positions of these two clusters, I will advocate using System.arraycopy(src, srcpos, dest, destpos, len), since it is native in the Java and its running speed is very fast.

    class Solution {
        public void rotate(int[] nums, int k) {
            if(nums==null) return;
            int modular= k % nums.length;
            if(modular == 0){
            int [] arr1 = new int[modular];

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.