LeetCode:Next Permutation
Posted walker lee
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode:Next Permutation相关的知识,希望对你有一定的参考价值。
Next Permutation
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
Subscribe to see which companies asked this question
思路:
下一个排列数,定义:比当前数大的最小数。
1.从左往右找到第一个“顺序”,即nums[i-1] <nums[i],因此nums[i,n-1]都是“逆序”;
2.从定义可知,我们要从[i,n-1]中找一个最小的数与nums[i-1]交往,然后将nums[i,n-1]“顺序”排序即可。
如:nums = [6,2,5,4,3,1], n = 6;
由1)找到i = 2,nums[2,5] = [5,4,3,1]是“逆序”;
由2)交换后得 nums=[6,3,5,4,2,1],再将[i, n-1]顺序,得解[6,3,1,2,4,5];
由于[i, n-1]已是逆序,直接逆序就变成“顺序”,时间O(n),即总时间O(n);
java code:
public class Solution { public void nextPermutation(int[] nums) { int n = nums.length; int i = n-1; // 从左到右,找到第一个“顺序”位置 while(i > 0) { if(nums[i-1] < nums[i]) break; i--; } if(i==0) { reverse(nums, 0, n-1); return; } // 找到第一个大于i位置值的下标j,并与i位置值交换 int j = n-1; int val = nums[i-1]; while(i < j && val >= nums[j]) j--; swap(nums, i-1, j); // 逆序[i,n-1]部分 reverse(nums, i, n-1); } // 自定义函数:逆序 void reverse(int[] nums, int lo, int hi) { while(lo < hi) { swap(nums, lo, hi); lo++;hi--; } } // 交换 void swap(int[] nums, int lo, int hi) { nums[lo] ^= nums[hi]; nums[hi] ^= nums[lo]; nums[lo] ^= nums[hi]; } }
以上是关于LeetCode:Next Permutation的主要内容,如果未能解决你的问题,请参考以下文章
[LeetCode] Next Greater Element II