Next Permutation
Description
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 and use only constant extra memory.
Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
- Example 1
Input: 1,2,3
Output: 1,3,2
- Example 2
Input: 3,2,1
Output: 1,2,3
- Example 3
Input: 1,1,5
Output: 1,5,1
Solution
字典排序类的问题,肯定会涉及翻转。
public class Solution {
public void nextPermutation(int[] nums) {
int i = nums.length - 2;
while(i>=0&& nums[i+1]<=nums[i]){
i--;
}
if(i>=0){
int f1=nums.length-1;
while(f1>=0&&nums[i]>=nums[f1])
{f1--;}
swap(nums,i,f1);
}
reverse(nums,i+1);
}
private void reverse(int[] nums, int start) {
int i = start, j = nums.length - 1;
while (i < j) {
swap(nums, i, j);
i++;
j--;
}
}
private void swap(int[] nums, int s, int t) {
int temp = nums[s];
nums[s] = nums[t];
nums[t] = temp;
}
}
RuntimeError的解法
class Solution {
public void nextPermutation(int[] nums) {
int len=nums.length;
int f1=len-2,f2=-1,f3=0;
for(int i=len-2;i>=0;i--){
if(nums[i+1]>nums[i])
f2=i;
break;
}
if(f2==-1){
reverse(nums,0,len-1);
return ;
}
for (int i=len-1;i>=0;i--){
if(nums[i]>nums[f2]){
swap(nums,i,f2);
f3=i+1;}
break;
}
reverse(nums,f3,len-1);
}
void swap(int[]nums,int m1,int m2){
int mid=0;
mid=nums[m1];
nums[m1]=nums[m2];
nums[m2]=mid;
}
void reverse(int[]nums,int m1,int m2){
int i=m1,j=m2;
while(i<j){
swap(nums,i,j);
}
i++;
j--;
}
}