LeetCode 31. Next Permutation
来源:互联网 发布:沈阳网络方面的兼职 编辑:程序博客网 时间:2024/06/05 07:21
问题描述
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
问题描述:
找出当前排列的下一个值。可以将当前数组认为是一个字符串,比较的时候是依次比较大小,得到只比他大一个的数。
解决方法:
比当前数组值只大一个的是:从最后一位开始找到第一个不是不是递增的数值,然后从递增的支付串中找出第一个比当前值大交换位置。然后将后面的位置中的所有的值进行升序排序就好。
例如: 2137540.下一个值应该是 首先找到 3,然后从3后面的值当中找到第一个比他大的值4,交换位置得到 2147530.然后把4后面的数进行升序排序得到 2140357。
代码实现:
public void nextPermutation(int[] nums) { int index = nums.length - 2; while (index >= 0 && nums[index] >= nums[index + 1]) { index--; } if (index < 0) { reverse(nums, 0, nums.length - 1); } else { //从index+1 开始找出第一个 大于当前indx值的数 int lastIndex = nums.length - 1; while (nums[lastIndex] <= nums[index] && lastIndex > index) { lastIndex--; } int temp = nums[index]; nums[index] = nums[lastIndex]; nums[lastIndex] = temp; reverse(nums, index + 1, nums.length - 1); } } /** * 交换两个数 * * @param nums * @param left * @param right */ private void swap(int nums[], int left, int right) { int temp = nums[left]; nums[left] = nums[right]; nums[right] = temp; } /** * 将两个数进行变化 * * @param nums * @param left * @param right */ protected void reverse(int nums[], int left, int right) { while (right > left) { swap(nums, left, right); left++; right--; } }
遇到的问题:
在做的过程中遇到的问题是:
确定第一个值的位置,nums[index] >= nums[index + 1]。容易忽略这个 = 。等于也需要过滤掉。
然后是后期的排序,由于这个值是升序的,所以可以用一个交换,从而将复杂度降到O(N).
- [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
- TBD ( Track-before-detect )
- JDBC
- TableViewCell的几种重用方式的区别
- HTML5 更改audio src路径后,获取duration为NaN的解决方法
- Jackson解析多层嵌套
- LeetCode 31. Next Permutation
- MongoDB aggregate,mapreduce,聚合命令的区别
- Android 6.0 解决recyclerview 在 scrollview 中不能全部显示,高度不正常的问题
- 在Ubuntu14.04上下载NDK和使用OLLVM混淆
- 【转】排除被冲销的物料凭证
- linux常用命令
- Dom4J 使用流程、拾遗
- [IoC容器Unity]第一回:Unity预览
- ES6中class与symbol简介