# leetcode (31) Next Permutation

146人阅读 评论(0)

Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.

If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).

The replacement must be in-place, do not allocate extra memory.

Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1

（1）从后向前，找到第一个i，满足nums[i] < nums[i+1]；若找不到满足的i，直接翻转数组即是所求。

（2）从后向前，numsSize-1到i之间，找到第一个比nums[i]大的数，索引位j

（3）交换nums[i]和nums[j]

（4）将nums[i]之后的数进行一个排序

（5）最后所得的数就是下一个排列。

#include <stdio.h>

void quickSort(int *nums, int start, int end) {
if (start >= end) return;
int flag = nums[start];
int left = start;
int right = end;
while (left < right) {
while(left < right && nums[right] >= flag) {
right--;
}
if(left < right) {
nums[left] = nums[right];
}
while(left < right && nums[left] <= flag) {
left++;
}
if(left < right) {
nums[right] = nums[left];
}
}
nums[left] = flag;
quickSort(nums, start, left-1);
quickSort(nums, left+1, end);
}

void nextPermutation(int* nums, int numsSize) {
int position = -1;
for (int i = numsSize-1; i > 0; i--) {
if (nums[i] > nums[i-1]) {
position = i-1;
break;
}
}
if (position == -1) {
for (int i = 0; i < numsSize/2; i++) {
int tmp = nums[i];
nums[i] = nums[numsSize-i-1];
nums[numsSize-i-1] = tmp;
}
return;
}
for (int i = numsSize-1; i > 0; i--) {
if (nums[i] > nums[position]) {
int tmp = nums[position];
nums[position] = nums[i];
nums[i] = tmp;
break;
}
}
quickSort(nums, position+1, numsSize-1);
}

int main() {
int nums[5] = {1,2,5,4,3};
//quickSort(nums, 0, 4);
nextPermutation(nums, 5);
for(int i = 0; i < 5; i++) {
printf("%d\n", nums[i]);
}
}

1
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：81042次
• 积分：1584
• 等级：
• 排名：千里之外
• 原创：70篇
• 转载：17篇
• 译文：0篇
• 评论：78条
最新评论