Day4
This commit is contained in:
11
189. Rotate Array/189. Rotate Array.csproj
Normal file
11
189. Rotate Array/189. Rotate Array.csproj
Normal 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>
|
||||
12
189. Rotate Array/Program.cs
Normal file
12
189. Rotate Array/Program.cs
Normal 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));
|
||||
}
|
||||
}
|
||||
}
|
||||
34
189. Rotate Array/Solution.cs
Normal file
34
189. Rotate Array/Solution.cs
Normal 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);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user