-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.cs
More file actions
45 lines (42 loc) · 1.01 KB
/
Solution.cs
File metadata and controls
45 lines (42 loc) · 1.01 KB
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
public class Solution
{
public void NextPermutation(int[] nums)
{
int n = nums.Length;
int swapIndex = -1;
for (int i = 1; i < n; i++)
{
if (nums[i] > nums[i - 1])
{
swapIndex = i;
}
}
if (swapIndex == -1)
{
Array.Reverse(nums);
return;
}
// find min to swap
int min = swapIndex;
for (int i = swapIndex + 1; i < n; i++)
{
if (nums[i] > nums[swapIndex - 1] && nums[i] < nums[min])
{
min = i;
}
}
// swap
(nums[min], nums[swapIndex - 1]) = (nums[swapIndex - 1], nums[min]);
// sort remain
for (int i = swapIndex; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
if (nums[i] > nums[j])
{
(nums[i], nums[j]) = (nums[j], nums[i]);
}
}
}
}
}