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; }