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.題目的意思是找到當前元素排列的‘下一個排列’。那麼什麼叫‘下一個排列呢’?這裏舉個例子,好比說元素1,2,3。它們的全排列是‘1,2,3’,‘1,3,2’,‘2,1,3’,‘2,3,1’,‘3,1,2’,‘3,2,1’所以好比求‘123’的下一個排列,就應該返回‘1,3,2’.
若是當前的序列不存在‘下一個排列’,那麼就返回徹底升序的第一個排列。數組例子: 左側一列是輸入,右側是正確的輸出:
1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1spa
public void nextPermutation(int[] nums) { int length = nums.length; int i= length-2; while(i>=0 && nums[i+1] <= nums[i])i--; if(i >= 0){ int j = length -1; while(j >= 0 && nums[j] <= nums[i])j--; swap(nums,i,j); } reverse(nums,i+1); } public void reverse(int[] nums,int start){ int end = nums.length-1; while(start < end){ swap(nums,start,end); start ++; end --; } } public void swap(int[] nums,int i,int j){ int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; }