这里我在一些临时数组的帮助下旋转数组
还有其他更好的方法来改进下面的数组旋转代码吗?我是数据结构的新手,如何发现这样的代码的时间复杂性?
class Arrayrotation {
public int[] inserttemp(int b[], int move, int len) {
int c[] = new int[move];
for (int i = 0; i < move; i++) {
c[i] = b[i];
//System.out.println(c[i]);
}
return c;
}
public int[] rotate(int b[], int move, int len, int d[]) {
int orglen = move;
int[] a = new int[len - orglen];
int k = 0;
for (int i = 0; i < b.length; i++) {
if (move < b.length) {
b[i] = b[move++];
} else if (move >= b.length) {
b[i] = d[k++];
}
}
System.out.println(Arrays.toString(b));
return b;
}
public static void main(String args[]) {
Arrayrotation a = new Arrayrotation();
int[] b = { 1,2,3,4,5,6,7,8,9};
int rotate = 3;
int[] d;
int[] f;
d = a.inserttemp(b, rotate, b.length);
a.rotate(b, rotate, b.length, d);
}
}
class RotateRight {
public static void main(String[] args) {
//Initialize array
int [] arr = new int [] {1, 2, 3, 4, 5};
//n determine the number of times an array should be rotated.
int n = 3;
//Displays original array
System.out.println("Original array: ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
//Rotate the given array by n times toward right
for(int i = 0; i < n; i++){
int j, last;
//Stores the last element of array
last = arr[arr.length-1];
for(j = arr.length-1; j > 0; j--){
//Shift element of array by one
arr[j] = arr[j-1];
}
//Last element of array will be added to the start of array.
arr[0] = last;
}
System.out.println();
//Displays resulting array after rotation
System.out.println("Array after right rotation: ");
for(int i = 0; i< arr.length; i++){
System.out.print(arr[i] + " ");
}
}
}
- 原始数组:1 2 3 4 5
- 右旋转后的数组:3 4 5 1 2