-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path189.RotateArray.cs
52 lines (48 loc) · 1.18 KB
/
189.RotateArray.cs
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
using System;
public class Solution {
public void Rotate(int[] nums, int k) {
if (nums.Length == 0 || k % nums.Length == 0) return;
k = k % nums.Length;
Algo2(nums, k);
}
private void Algo1(int[] nums, int k)
{
var copy = new int[nums.Length];
Array.Copy(nums, copy, nums.Length);
var j = nums.Length - k;
for (var i = 0; i < nums.Length; ++i)
{
if (j == nums.Length) j = 0;
nums[i] = copy[j];
++j;
}
}
private void Algo2(int[] nums, int k)
{
var gcd = Gcd(nums.Length, k);
var count = nums.Length / gcd;
for (var i = 0; i < gcd; ++i)
{
var p = i;
var first = nums[p];
for (var j = 0; j + 1 < count; ++j)
{
var q = p - k;
if (q < 0) q += nums.Length;
nums[p] = nums[q];
p = q;
}
nums[i + k] = first;
}
}
private int Gcd(int m, int n)
{
while (n > 0)
{
var x = m % n;
m = n;
n = x;
}
return m;
}
}