31. Next Permutation

This commit is contained in:
2026-03-25 20:28:57 +03:00
parent 48d637475f
commit 8c963d3aa2
4 changed files with 72 additions and 0 deletions

View 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>

View 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;
}

View 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);
}
}