31. Next Permutation
来源:互联网 发布:中山大学网络服务中心 编辑:程序博客网 时间:2024/06/16 22:53
题目
求下一个排序数
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,23,2,1 → 1,2,31,1,5 → 1,5,1
题目分析
看如下序列:
3 5 4 2 1
求其下一个排序数的思路:
1. 逆序搜索,找到第一个满足
2. 交换 nums[i-1] 和 i>=1子序列的最小值。 最小值为 4;即交换 3 和 4,得到的序列为:4 5 3 2 1
3. 将i>=1的序列反转,即 4 1 2 3 5
代码
时间复杂度为O(n),空间复杂度为O(1)。
public class Solution { public void NextPermutation(int[] nums) { if(nums.Length<=1) return; int i = findIndex(nums); if(i==0)//no existence nums[i-1]<nums[i] sortReverseNums(nums,0,nums.Length-1); else { int swap1 = findSwapIndex(nums,i); swap(nums,i-1,swap1); sortReverseNums(nums,i,nums.Length-1); } } //find the first nums[i-1]<nums[i] of i private int findIndex(int[] nums){ int n=nums.Length-1; while(n>0){ if(nums[n-1]<nums[n]) break; n--; } return n; } //find the swap index //assert: i>=1 private int findSwapIndex(int[] nums, int i){ int n=nums.Length-1; int swap1=nums[i-1]; int index; for(index=n; index>=i;index--){ if(swap1<nums[index]) break; } return index; } private void swap(int[] nums, int i, int j){ int tmp=nums[i]; nums[i]=nums[j]; nums[j]=tmp; } private void sortReverseNums(int[] nums, int start, int end){ for(int i=start; i<=(start+end)/2;i++){ swap(nums,i,start+end-i); } }}
阅读全文
2 0
- [LeetCode]31.Next Permutation
- LeetCode --- 31. Next Permutation
- [Leetcode] 31. Next Permutation
- LeetCode 31.Next Permutation
- 31. Next Permutation
- [leetcode] 31.Next Permutation
- [leetcode] 31. Next Permutation
- *LeetCode 31. Next Permutation
- 31. Next Permutation
- Leetcode 31. Next Permutation
- 31. Next Permutation
- 31. Next Permutation
- 31. Next Permutation
- leetcode 31. Next Permutation
- 31. Next Permutation LeetCode
- 31. Next Permutation
- 31. Next Permutation
- 31. Next Permutation
- dialog级联写法
- CSU-ACM2017暑期训练1-Debug与STL C
- MySharedpreference
- 冲突域和广播域的区分
- HTML基础汇总
- 31. Next Permutation
- 用IDEA开发简单的Servlet
- MFC控件之listControl简单应用
- Javascript高级程序设计重刷——基础知识
- 在centos7系统下配置LAMP详解教程
- python绘图:matplotlib和pandas的应用
- HDU1176 DP
- 线程和进程的区别(来自知乎)
- 拓扑排序入门确定比赛名次