This commit is contained in:
Electrominch
2022-10-06 00:46:00 +03:00
parent 062e03bdbf
commit cb2f99c3a8
21 changed files with 434 additions and 4 deletions

View File

@@ -0,0 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<RootNamespace>_189._Rotate_Array</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>

View File

@@ -0,0 +1,12 @@
namespace _189._Rotate_Array
{
internal class Program
{
static void Main(string[] args)
{
var arr = new int[] { 1, 2, 3, 4, 5, 6};
new Solution().Rotate(arr, 3);
Console.WriteLine(String.Join(" ", arr));
}
}
}

View File

@@ -0,0 +1,34 @@
namespace _189._Rotate_Array;
public class Solution
{
public void Rotate(int[] nums, int k)
{
k %= nums.Length;
if (k == 0)
return;
int oneCycleLen = nums.Length/ GCD(nums.Length, k);
for (int i = 0; i < nums.Length / oneCycleLen; i++)
MoveTo(nums, nums[i], i + k, k, oneCycleLen);
}
private static void MoveTo(int[] array, int value, int to, int step, int curLen)
{
while (curLen-- > 0)
{
if (to >= array.Length)
to -= array.Length;
int buf = array[to];
array[to] = value;
to += step;
value = buf;
}
}
private static int GCD(int a, int b)
{
return b == 0 ? a : GCD(b, a % b);
}
}