1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
| public class Solution {
public static void tripleReverse(int[] nums, int K) { int length = nums.length; reverse(nums, 0, length - K - 1); reverse(nums, length - K, length - 1); reverse(nums, 0, length - 1); }
private static void reverse(int[] nums, int start, int end) { int sum = start + end; int temp; for (int i = start; i <= (start + end) / 2; ++i) { temp = nums[i]; nums[i] = nums[sum - i]; nums[sum - i] = temp; } }
public static void doubleSwap(int[] nums, int K) { int start = 0; int end = nums.length; int middle = nums.length - K; int i = middle; int temp;
while (true) { temp = nums[start]; nums[start] = nums[i]; nums[i] = temp; ++start; if (++i == end) { if (start == middle) { break; } i = middle; } else if (start == middle) { middle = i; } } }
public static void rotate_GCD(int nums[], int K) { int length = nums.length; int front, post, temp; for (int i = 0; i < GCD(length, K); ++i) { temp = nums[i]; front = i; while (true) { post = front + K; if (post >= length) { post = post - length; } if (post == i) { break; } nums[front] = nums[post]; front = post; } nums[front] = temp; } }
private static int GCD(int a, int b) { if (b == 0) { return a; } else { return GCD(b, a % b); } }
public static void main(String[] args) { int[] array = new int[1_0000_0000]; for (int i = 0; i < 1_0000_0000; ++i) { array[i] = i; }
long startTime; long durationNanoSecond; double durationMicroSecond;
startTime = System.nanoTime(); tripleReverse(array, 1000000); durationNanoSecond = System.nanoTime() - startTime; durationMicroSecond = durationNanoSecond / 1_000; System.out.println(String.format("[tripleReverse]Time:%f 微秒", durationMicroSecond));
startTime = System.nanoTime(); doubleSwap(array, 1000000); durationNanoSecond = System.nanoTime() - startTime; durationMicroSecond = durationNanoSecond / 1_000; System.out.println(String.format("[doubleSwap]Time:%f 微秒", durationMicroSecond));
startTime = System.nanoTime(); rotate_GCD(array, 1000000); durationNanoSecond = System.nanoTime() - startTime; durationMicroSecond = durationNanoSecond / 1_000; System.out.println(String.format("[rotate_GCD]Time:%f 微秒", durationMicroSecond));
System.out.print("[result]"); for (int i = 0; i < 10; i++) { System.out.printf("%d,", array[i]); } } }
|