Leetcode- Rotate Array to right by K steps (java)

Tags: , ,

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].

How many different ways do you know to solve this problem?

Analysis

It is easy to use an intermediate array to solve this problem. Suppose the original array is A, the new array is B, we will copy 

A[0:n-k -1] to B[k:n-1], and A[n – k:n-1] to B[0:k – 1], then we copy all the elements in B back to Array A using System.arrayCopy.

See the following implementation in Java:

Comment is closed.