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).spa
The replacement must be in-place, do not allocate extra memory.code
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
blog
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 }
本題主要考查細心程度。it