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
- LeetCode 31: Next Permutation
- [leetcode 31] Next Permutation
- LeetCode(31) Next Permutation
- LeetCode---(31) Next Permutation
- 31-m-Next Permutation
- leetcode 31 -- Next Permutation
- leetcode 31: Next Permutation
- Leecode#31 Next Permutation
- LeetCode(31) Next Permutation
- LeetCode-31 Next Permutation
- Leetcode#31||Next Permutation
- 31Next Permutation
- 31 Next Permutation
- LeetCode 31: Next Permutation
- [31]Next Permutation
- 31 Next Permutation
- 31、Next Permutation
- LeetCode(31)-Next Permutation
- 关于使用VS生成Lua 5.2.3编译器与解释器 动态库 静态库
- matplotlib绘图实例
- 错误:Assertion failure in -[UICollectionView _createPreparedSupplementaryViewForElementOfKind:atIndexP
- JSP获取异常信息的exception对象
- linux多屏配置文件 xorg.conf 官方配置文件说明翻译
- 31、Next Permutation
- oj1991: C语言实验——大小写转换
- c# task run in background
- pgsql批量修改table/view的owner
- 卡尔曼滤波的原理说明
- linux下/etc/hosts 和hostname文件的区别
- Javascript 面向对象编程(一):封装
- iOS常用的第三方库
- java模拟登陆正方教务管理系统