Next Permutationgit
問題:數組
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.ide
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.spa
思路:code
個人代碼:blog
public class Solution { public void nextPermutation(int[] num) { if(num==null || num.length<2) return; int i = num.length-2; int j = num.length-1; while(i >= 0) { if(num[i] < num[i+1]) break; i--; } if(i == -1) { reverseArray(num, 0, num.length-1); return; } while(j > i) { if(num[j] > num[i]) break; j--; } int tmp = num[i]; num[i] = num[j]; num[j] = tmp; reverseArray(num, i+1, num.length-1); } public void reverseArray(int[] num, int begin, int end) { while(begin < end) { int tmp = num[begin]; num[begin] = num[end]; num[end] = tmp; begin++; end--; } } }
學習之處:數學