首页 > 代码库 > 31. Next Permutation

31. 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

 

 
 本题开始的时候题意没有读懂,看了别人的解释才看懂,大致思路是
1.从右面往左面遍历,如果找到数组下一个的值小于(不包括等于)当前值(即本来是从右往左是递增序列,但是被打断的元素)提取出来
2.再一次从右往左遍历,直到当前数组值大于提取出来的值后,交换这两个位置。
3.将从右到左不断递增的数组区间反转。
代码如下:
 1 public class Solution {
 2     public void nextPermutation(int[] nums) {
 3         int index = nums.length;
 4         for(int i=nums.length-1;i>=1;i--){
 5             if(nums[i-1]>=nums[i]) continue;
 6             index = i-1;
 7             break;
 8         }
 9         if(index!=nums.length){
10             for(int i=nums.length-1;i>=index;i--){
11             if(nums[i]<=nums[index]) continue;
12             swap(nums,index,i);
13             break;
14             }
15             reverse(nums,index+1,nums.length-1);
16         }else{
17             reverse(nums,0,nums.length-1);
18         }
19     }
20     public void swap(int[] nums,int i,int j){
21         int temp = nums[i];
22         nums[i] = nums[j];
23         nums[j] = temp;
24     }
25     public void reverse(int[] nums,int left,int right){
26         while(left<right){
27             swap(nums,left++,right--);
28         }
29     }
30 }

本题主要考查细心程度。

31. Next Permutation