leetcode 31. Next Permutation
来源:互联网 发布:苹果电脑直播音效软件 编辑:程序博客网 时间:2024/06/06 04:13
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,2,3 对于1开头的排列,23升序 改成32就增大
3,2,1 对于3开头的排列 21降序 已经是最大
1,1,5 对于1开头的排列 15升序 改成51就可以增大
所以关键在与后缀的排列是否有“上升空间” 一个降序字符串是没有上升空间的了 所以应该从字符串尾部往前走 一直升就接着走 直到遇到峰值下降 考虑怎么修改
比如: 1,4,5,3,2
2走到3 升序 接着走
3走到5 升序 接着走
5走到4 降序 此时说明532没有上升空间 但是4532有上升空间
4532 首先把5调成第一位 然后4 3 2排成升序(升序最小嘛)也就是5234就是4532的下一位
假设是42531
原始字符串: |4|2|5|3|1|(那么我们的目标字符串是:|4|3|1|2|5|)**第一步: 找到第一降序位置(从尾往头走哈)5 说明其前面的2已经尽全力了 需要替换的是2开始的序列 需要拿532中比2大且最接近2的那个数 也就是3去作为开头 |4|3|5|2|1| 由于原来的531是降序 将3替换为2 由于3是“比2大且最接近2的数” 所以新来的2**重点内容**一定比5小 (!!这里可以证明一下为什么新的子集仍然是降序 为什么新来的2一定比1大)第二步:将521逆序 |4|3|1|2|5|原地逆序就不难了
public void nextPermutation(int[] nums) { int i = nums.length - 1; while(i > 0 && nums[i-1] >= nums[i]) i--; if(i > 0){ int baseValue = Integer.MAX_VALUE; int baseIndex = i-1; for(int j = i;j<nums.length;j++){ if(nums[j] > nums[i-1] && nums[j] <= baseValue){ baseValue = nums[j]; baseIndex = j; } } swap(nums, i-1, baseIndex); } int j = nums.length - 1; while(i < j){ swap(nums, i, j); i++; j--; } } public void swap(int[] nums,int indexi,int indexj){ int temp = nums[indexi]; nums[indexi] = nums[indexj]; nums[indexj] = temp; }
- [LeetCode]31.Next Permutation
- LeetCode --- 31. Next Permutation
- [Leetcode] 31. Next Permutation
- LeetCode 31.Next Permutation
- [leetcode] 31.Next Permutation
- [leetcode] 31. Next Permutation
- *LeetCode 31. Next Permutation
- Leetcode 31. Next Permutation
- leetcode 31. Next Permutation
- 31. Next Permutation LeetCode
- leetcode 31. Next Permutation
- leetcode 31. Next Permutation
- [LeetCode]31. Next Permutation
- [LeetCode]31. Next Permutation
- LeetCode 31. Next Permutation
- 【leetcode】31. Next Permutation
- LeetCode *** 31. Next Permutation
- leetcode 31. Next Permutation
- 布局神器display:table-cell
- React Native开发环境配置
- [转载]STL学习之Vector
- 版本迭代,上传ipa时的小毛病
- git 切换分支,pull分支,提交分支
- leetcode 31. Next Permutation
- Eclipse中调节字体大小、颜色与背景色
- android 与java服务器进行RSA+AES加密通信
- 人生苦短,我用 Python
- 建立自己的MIT App Inventer 2的网络微数据库网络后台
- macOS下信号量semaphore部分函数失效的问题
- 把已经存在的项目上传到github
- 关于使用Android Studio 2.1+ 出现AGPBI错误的处理
- 177.Convert Sorted Array to Binary Search Tree With Minimal Height-把排序数组转换为高度最小的二叉搜索树(容易题)