31、Next Permutation

来源:互联网 发布:达内java培训视频下载 编辑:程序博客网 时间:2024/09/21 06:34

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


因为是寻找下一个大的,下一个大的一定是从后面开始往前找,直到出现不是逆序排列的点。第一种情况可能没有,也就是当前为最大,那么就输出最小,还有一种情况就是找到了那个点。

int comp(void const *a, void const *b){return *(int*)a - *(int*)b;}void nextPermutation(int* nums, int numsSize){    int i, j, k;int max, min, temp;for(j=numsSize-2, max=nums[numsSize-1];j>=0 && nums[j] >= max;j--)max = nums[j];if(j < 0){//这里可以进行优化,因为j<0的情况一定是逆序所以收尾交换就可以了, 最后发现反而更加慢, //时间复杂度并不是唯一决定程序快慢的因素qsort(nums, numsSize, sizeof(int), comp); /* i = 0; j = numsSize-1;while(i<j){temp = nums[i];nums[i++] = nums[j];nums[j--] = temp;} */}else // nums[j] < max 后面有大的数{min = nums[j];qsort(nums+j,numsSize-j,sizeof(int),comp);for(i=j;i<numsSize;i++){if(nums[i] == min){while(nums[++i] == min);break;}}//执行一层的插入排序max = nums[i]; for(k=i-1;k>=j;k--)nums[k+1] = nums[k];nums[k+1] = max;}}
0 0
原创粉丝点击