var rotate = function(nums, k) { const n = nums.length; const newArr = newArray(n); for (let i = 0; i < n; ++i) { newArr[(i + k) % n] = nums[i]; } for (let i = 0; i < n; ++i) { nums[i] = newArr[i]; } };
[sol1-Golang]
1 2 3 4 5 6 7
funcrotate(nums []int, k int) { newNums := make([]int, len(nums)) for i, v := range nums { newNums[(i+k)%len(nums)] = v } copy(nums, newNums) }
[sol1-C]
1 2 3 4 5 6 7 8 9
voidrotate(int* nums, int numsSize, int k) { int newArr[numsSize]; for (int i = 0; i < numsSize; ++i) { newArr[(i + k) % numsSize] = nums[i]; } for (int i = 0; i < numsSize; ++i) { nums[i] = newArr[i]; } }
classSolution { public: voidrotate(vector<int>& nums, int k){ int n = nums.size(); k = k % n; int count = gcd(k, n); for (int start = 0; start < count; ++start) { int current = start; int prev = nums[start]; do { int next = (current + k) % n; swap(nums[next], prev); current = next; } while (start != current); } } };
classSolution { publicvoidrotate(int[] nums, int k) { intn= nums.length; k = k % n; intcount= gcd(k, n); for (intstart=0; start < count; ++start) { intcurrent= start; intprev= nums[start]; do { intnext= (current + k) % n; inttemp= nums[next]; nums[next] = prev; prev = temp; current = next; } while (start != current); } }
publicintgcd(int x, int y) { return y > 0 ? gcd(y, x % y) : x; } }
[sol2-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
constgcd = (x, y) => y ? gcd(y, x % y) : x;
var rotate = function(nums, k) { const n = nums.length; k = k % n; let count = gcd(k, n); for (let start = 0; start < count; ++start) { let current = start; let prev = nums[start]; do { const next = (current + k) % n; const temp = nums[next]; nums[next] = prev; prev = temp; current = next; } while (start !== current); } };
[sol2-Golang]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
funcrotate(nums []int, k int) { n := len(nums) k %= n for start, count := 0, gcd(k, n); start < count; start++ { pre, cur := nums[start], start for ok := true; ok; ok = cur != start { next := (cur + k) % n nums[next], pre, cur = pre, nums[next], next } } }
funcgcd(a, b int)int { for a != 0 { a, b = b%a, a } return b }
intgcd(int a, int b) { return b ? gcd(b, a % b) : a; }
voidswap(int* a, int* b) { int t = *a; *a = *b, *b = t; }
voidrotate(int* nums, int numsSize, int k) { k = k % numsSize; int count = gcd(k, numsSize); for (int start = 0; start < count; ++start) { int current = start; int prev = nums[start]; do { int next = (current + k) % numsSize; swap(&nums[next], &prev); current = next; } while (start != current); } }