【題目】算法
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.spa
If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).code
The replacement must be in-place, do not allocate extra memory.blog
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
索引
【analyze】it
1.從後往前找(找到第一個元素的值比後序的元素值 小,索引記爲pivot)io
2.再從後往前找(找到第一個元素的值比pivot處的元素大的值(不要=),索引記爲large),交換pivot和largeclass
3.將pivot+1-end之間的元素逆轉call
【算法】next
public class Solution { public void nextPermutation(int[] nums) { int len=nums.length; int pivot=len-1; while(pivot>0) { if(nums[pivot]>nums[pivot-1]) break; pivot--; } if(pivot>0) { pivot--; int large=len-1; while(nums[pivot]>=nums[large]) //找出比pivot元素值大的large large--; swap(nums,pivot,large); reverse(nums,pivot+1,len-1); }else { reverse(nums,0,len-1); } } //將數據區間的元素逆轉 public void reverse(int[] nums,int first,int end) { for(int i=0;i<(end-first+1)/2;i++) { swap(nums,first+i,end-i); } } //交換元素 public void swap(int[] nums,int a,int b) { int temp=nums[a]; nums[a]=nums[b]; nums[b]=temp; } }