Next Permutation
来源:互联网 发布:手机淘宝国际版 编辑:程序博客网 时间:2024/06/05 09:54
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
Example : 6, 8, 9, 5,4,3,2
1. From right to left, find the first element that is not in an ascending order. In this example, the element is 8.
2. Form right to left, find the first element that is bigger than the element we found in step 1. In this example, it is 9. Swap these two numbers.
6,8,9,5,4,3,2 -> 6,9,8,5,4,3,2
3.Reverse the list from the next index of the number found in step 1.
6,9,8,5,4,3,2 -> 6,9,2,3,4,5,8
Special Example: 5,4,3,2,1
The next permutation should be 1,2,3,4,5
public class Solution { public void nextPermutation(int[] nums) { int i = 0; for (i = nums.length - 2; i >=0; i--) if (nums[i] < nums[i + 1]) break; if (i == -1) { reverse(nums, 0, nums.length - 1); return; } int j = 0; for (j = nums.length - 1; j >=i + 1; j--) { if (nums[j] > nums[i]) { break; } } int temp = nums[j]; nums[j] = nums[i]; nums[i] = temp; reverse(nums, i + 1, nums.length - 1); return; } private void reverse(int[] nums, int start, int end) { while (start < end) { int temp = nums[start]; nums[start] = nums[end]; nums[end] = temp; start++; end--; } }}
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- 汤原身份证号码户籍地址信息查询
- hadoop参考链接
- 汤原在逃犯罪人员信息记录查询
- androidUI那些事(一)
- mysql中导入数据load data在myisam与innodb区别
- Next Permutation
- opencv关于存取图像像素操作的汇总
- c++ 根据编译时间的版本号输出
- 数据库常用相关(一)
- 乐乐音乐播放器(四) 日志文件
- Unix时间戳转换成Date
- DOS命令本地jar包添加到Maven本地仓库
- RTMP中FLV流到标准h264、aac的转换b
- sizeof 数据对齐问题