- public static void main(String[] args) {
- int shift = 3;
- int[] arr;
- arr = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
- shiftLeft(arr, shift);
- System.out.printf("向左移动%d %s%n", shift, Arrays.toString(arr));
- arr = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
- shiftRight(arr, shift);
- System.out.printf("向右移动%d %s%n", shift, Arrays.toString(arr));
- }
- /**
- * 向右移动 要求 arr != null && arr.length >= 1 && shift >= 0
- */
- public static void shiftRight(int[] arr, int shift) {
- if ((shift %= arr.length) == 0) {
- return;
- }
- int len = arr.length;
- int step = GCD(len, shift);
- int round = len / step;
- for (int i = 0; i < step; i++) {
- int t = arr[(i + shift * round) % len], index1 = 0, index2 = 0;
- for (int j = round; j > 1; j--) {
- index2 = (i + shift * j - shift) % len;
- index1 = (index2 + shift) % len;
- arr[index1] = arr[index2];
- }
- arr[index2] = t;
- }
- }
- /**
- * 向左移动 要求 arr != null && arr.length >= 1 && shift >= 0
- */
- public static void shiftLeft(int[] arr, int shift) {
- if ((shift %= arr.length) == 0) {
- return;
- }
- int len = arr.length;
- int step = GCD(len, shift);
- int round = len / step;
- for (int i = 0; i < step; i++) {
- int t = arr[i], index1 = 0, index2 = 0;
- for (int j = 0; j < round - 1; j++) {
- index1 = (i + shift * j) % len;
- index2 = (index1 + shift) % len;
- arr[index1] = arr[index2];
- }
- arr[index2] = t;
- }
- }
- /**
- * 辗转相除法求最大公约数 要求 a > 0 && b > 0
- */
- public static int GCD(int a, int b) {
- while (b != 0) {
- int t = a;
- a = b;
- b = t % b;
- }
- return a;
- }
复制代码
如果您觉得我的回答还满意的话,请回复一下我
我的QQ:2355928351
如果您还有其他的入学前问题可以加我的QQ |