Next permutation
Total Accepted: 33595 submissions: 134095
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
If Such arrangement is not a possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
The replacement must is in-place, do not allocate extra memory.
Problem Solving Ideas:
The problem is not difficult, the key is to understand the meaning of the topic: if the nums as a number, that is, the return of the smallest number than the original number (if not (the original number is in descending order) is returned to order.
Not very difficult, Java implementation is as follows:
static public void Nextpermutation (int[] nums) {int index = nums.length-1;while (index >= 1) {if (Nums[index] > Nu Ms[index-1]) {int swapnum=nums[index-1],swapindex = Index+1;while (swapindex <= nums.length-1&& swapNum < ; Nums[swapindex]) Swapindex++;nums[index-1]=nums[swapindex-1];nums[swapindex-1]=swapnum;reverse (Nums,index); return;} index--;} Reverse (nums,0);} static void reverse (int[] Nums,int swapindex) {int[] swap=new int[nums.length-swapindex];for (int i=0;i<swap.length; i++) swap[i]=nums[nums.length-1-i];for (int i=0;i<swap.length;i++) nums[swapindex+i]=swap[i];}
Java for Leetcode 031 Next permutation