LeetCode#31. Next Permutation
来源:互联网 发布:value at risk python 编辑:程序博客网 时间:2024/06/06 02:12
对于Java党,对这个题目都理解了半天啊啊啊啊啊
题目:给定一个数组,求下一个字典序列
难度:Medium
思路:
字典序列: 1,2,3 -> 1,3,2 3,2,1 -> 1,2,3 1,2,4,3 -> 1,3,2,4所谓的求下一个字典排序,就是按照查字典的方式1.如果当前序列不是一个降序,则从后往前一定能找到一个元素位置为i,使得i位置对应的值小于i+1位置的值。2.找到这样的i之后,需要从后往前查找(直到i),找到第一个大于i位置元素的值,将两个位置的值进行交换3.交换之后,i位置之后的元素一定都是降序序列,需要对该降序序列进行一个反转(使得它成为一个升序序列)
- 代码:
1. 非递归方式
public class Solution { public void nextPermutation(int[] nums) { if(nums == null || nums.length <= 1){ return ; } int i = nums.length -1 ; //先从后往前找到一个最短的不是降序的子数组(找到一个i使得i后面的元素有比i位置元素大的值) for(; i >= 1; i--){ if(nums[i-1] < nums[i]){ break; } } if(i != 0){ swap(nums,i-1); } reverse(nums,i); } /** * 从后往前(直到i位置),找到第一个比nums[i]大的元素,两者进行交换 */ private void swap(int[] nums, int i){ System.out.print(i); for(int j = nums.length-1; j > i; j--){ if(nums[j] > nums[i]){ int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; break; } } } /** * 将i位置以及后面的元素以升序排列(这一段序列是降序的) */ private void reverse(int[] nums, int i){ System.out.print(i); int first = i; int last = nums.length-1; while(first < last){ int temp = nums[first]; nums[first] = nums[last]; nums[last] = temp; first++; last--; } }}
0 0
- [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
- 千兆网线做法和网线接法注意事项
- 一步一步学习 ReactNative + Redux(6)
- android studio 中实现二维码扫描
- 移动端禁止长按图片弹出系统功能列表和禁止文本选择
- string stringbuffer stringbuilder的执行效率
- LeetCode#31. Next Permutation
- 关于expected identifier or ‘(’ before***的错误
- 高德地图Android开发-环境配置
- 装修注意事项总结
- 读取HDFS上的文件时报错
- python2.7 x64版本下pymssql的安装及数据库连接代码
- Result Maps collection already contains value for cn.itcast.ssm.mapper.Items的原因及解决办法
- 循环队列的实现
- android开发之观察者模式的使用