Skip to content

Commit b770fde

Browse files
Refine
Signed-off-by: begeekmyfriend <begeekmyfriend@gmail.com>
1 parent ebdeffe commit b770fde

File tree

1 file changed

+23
-23
lines changed

1 file changed

+23
-23
lines changed

031_next_permutation/next_permutation.c

Lines changed: 23 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,21 @@
11
#include <stdio.h>
22
#include <stdlib.h>
33

4+
static inline void swap(int *a, int *b)
5+
{
6+
int tmp = *a;
7+
*a = *b;
8+
*b = tmp;
9+
}
10+
411
static void reverse(int *a, int size)
512
{
6-
int left = 0;
7-
int right = size - 1;
8-
while (left < right) {
9-
int tmp = a[left];
10-
a[left] = a[right];
11-
a[right] = tmp;
12-
left++;
13-
right--;
13+
int lo = 0;
14+
int hi = size - 1;
15+
while (lo < hi) {
16+
swap(a + lo, a + hi);
17+
lo++;
18+
hi--;
1419
}
1520
}
1621

@@ -20,24 +25,19 @@ static void nextPermutation(int* nums, int numsSize)
2025
return;
2126
}
2227

23-
int *p = nums + numsSize - 1;
24-
int *q = nums + numsSize - 1;
25-
26-
while (p != nums && *(p - 1) >= *p) {
27-
p--;
28+
int i = numsSize - 2;
29+
while (i >= 0 && nums[i] >= nums[i + 1]) {
30+
i--;
2831
}
2932

30-
if (p != nums) {
31-
int n = *(p - 1);
32-
while (*q <= n) {
33-
q--;
33+
if (i >= 0) {
34+
int j = numsSize - 1;
35+
while (j >= 0 && nums[j] <= nums[i]) {
36+
j--;
3437
}
35-
36-
int tmp = *q;
37-
*q = *(p - 1);
38-
*(p - 1) = tmp;
38+
swap(nums + i, nums + j);
3939
}
40-
reverse(p, numsSize - (p - nums));
40+
reverse(nums + i + 1, numsSize - i - 1);
4141
}
4242

4343
int main(int argc, char **argv)
@@ -56,7 +56,7 @@ int main(int argc, char **argv)
5656
nextPermutation(nums, argc - 1);
5757

5858
for (i = 0; i < argc - 1; i++) {
59-
printf("%d", nums[i]);
59+
printf("%d ", nums[i]);
6060
}
6161
putchar('\n');
6262

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy