31. Next Permutation
This commit is contained in:
11
31. Next Permutation/31. Next Permutation.csproj
Normal file
11
31. Next Permutation/31. Next Permutation.csproj
Normal file
@@ -0,0 +1,11 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<RootNamespace>_31._Next_Permutation</RootNamespace>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
</Project>
|
||||
30
31. Next Permutation/Program.cs
Normal file
30
31. Next Permutation/Program.cs
Normal file
@@ -0,0 +1,30 @@
|
||||
var sol = new Solution();
|
||||
|
||||
var cases = new (int[] input, int[] expected)[]
|
||||
{
|
||||
(new[] { 1, 2, 3 }, new[] { 1, 3, 2 }),
|
||||
(new[] { 3, 2, 1 }, new[] { 1, 2, 3 }),
|
||||
(new[] { 1, 1, 5 }, new[] { 1, 5, 1 })
|
||||
};
|
||||
|
||||
foreach (var (input, expected) in cases)
|
||||
{
|
||||
var nums = (int[])input.Clone();
|
||||
sol.NextPermutation(nums);
|
||||
var status = AreEqual(nums, expected) ? "ok" : "fail";
|
||||
Console.WriteLine($"{Format(input)} -> {Format(nums)} (expected: {Format(expected)}) {status}");
|
||||
}
|
||||
|
||||
static string Format(int[] nums) => $"[{string.Join(",", nums)}]";
|
||||
|
||||
static bool AreEqual(int[] left, int[] right)
|
||||
{
|
||||
if (left.Length != right.Length)
|
||||
return false;
|
||||
for (var i = 0; i < left.Length; i++)
|
||||
{
|
||||
if (left[i] != right[i])
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
17
31. Next Permutation/Solution.cs
Normal file
17
31. Next Permutation/Solution.cs
Normal file
@@ -0,0 +1,17 @@
|
||||
public class Solution
|
||||
{
|
||||
public void NextPermutation(int[] nums)
|
||||
{
|
||||
var i = nums.Length - 2;
|
||||
while(i >= 0 && nums[i] >= nums[i+1])
|
||||
i--;
|
||||
if(i >= 0)
|
||||
{
|
||||
var j = nums.Length - 1;
|
||||
while(nums[i] >= nums[j])
|
||||
j--;
|
||||
(nums[i], nums[j]) = (nums[j], nums[i]);
|
||||
}
|
||||
Array.Reverse(nums, i+1, nums.Length-i-1);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user