Problem Description
One kind of problem is that the whole array is translated, for example, the overall left or right to pan 3 lengths, similar to the solution of such problems many, the following is to try to use the Java language to give three solutions, imagine the problem is to shift an array to the right of the whole K units, even if translation before the array { 1,2,3,4,5,6,7}, after panning 3 lengths, the array is {5,6,7,1,2,3,4}.
Simple Thought
In general, the simplest method is to first create a new array and then assign the array one by one by law. As shown in the following code:
/** * The simplest algorithm, open up another number, copy it. * @param a input array * @param k move Steps * time complexity O (n) * space complexity O (n) */public static void Rotate1 (int[] A,int k) {int[] b = new int[a.length];for (int i=0;i<k;i++) {b[i]=a[a.length-k+i];} for (int j=0;j<a.length-k;j++) {b[j+k]=a[j];} System.arraycopy (b, 0, a, 0, a.length);}
The time complexity of this method is O (n), and the spatial complexity is O (n), which is the most common method we think of.
Bubbling Thought
Recalling the idea of the bubbling sorting algorithm I had previously learned, I felt that the problem was somewhat like, for example, the 5,6,7 bubbles up and 1,2,3,4 down to the bottom, so we can solve this problem with the idea of bubbling sort. As shown in the following code:
/** * Thought of bubble sorting algorithm * @param a input array * @param k move Steps * Time complexity O (n*k) * Space complexity O (1) */public static void Rotate2 (int[] a,int k) {for (int i=0;i<k;i++) {for (int j=a.length-k+i;j>i;j--) {int tmp=a[j];a[j]=a[j-1];a[j-1]=tmp;}}}
The time complexity of this method is O (n*k), the space complexity is O (1), with the help of the idea of bubbling sort.
Rotational Thinking
carefully study the array before and after the change we will find that the array is decomposed into two parts, then the two parts are rotated upside down, and finally merged into a large array and then rotated once, can be completed. As shown in the following code:
/** * * @param a input array * @param k move Steps * Time complexity O (N) * Space complexity O (1) */public static void Rotate3 (int[] a,int k) {reverse (a , 0,a.length-k-1); reverse (a,a.length-k,a.length-1); reverse (a,0,a.length-1);} public static void reverse (Int[]a,int start,int end) {for (int i=0;i< (end-start+1)/2;i++) {int Tmp=a[start+i];a[start +i]=a[end-i];a[end-i]=tmp;}}
The time complexity of this method is O (N), the space complexity is O (1), with the help of the idea of rotation, more ingenious.
Research on the whole moving problem of array elements