Problem:
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.
Here is some examples. Inputs is in the left-hand column and its corresponding outputs is in the right-hand column.
1,2,3
→1,3,2
3,2,1
→1,2,3
1,1,5
→1,5,1
Solution: In reverse lookup method, find the first descending number, such as 2321, the first decrement of the number is 2, and then the decrement number behind the smaller than the smallest number of the interchange, 2321 is 3221, and then the back of the number in ascending order, so just
The main idea: given an array, rearrange the numbers so that the number is larger than the original number, and this number is smaller than the original number of the collection of the smallest
Java source Code (365MS):
public class Solution {public void Nextpermutation (int[] nums) { int len=nums.length,i=len-1,j,tmp; while (i>0 && nums[i]<=nums[i-1]) i--; if (i>0) { j=len-1; while (Nums[j]<=nums[i-1]) j--; TMP=NUMS[J]; NUMS[J]=NUMS[I-1]; nums[i-1]=tmp; } j=len-1; while (i<j) { tmp=nums[i]; NUMS[I]=NUMS[J]; nums[j]=tmp; i++;j--;}}}
C Language Source code (14MS):
void Nextpermutation (int* nums, int numssize) { int j,i=numssize-1,tmp; while (i>0 && nums[i]<=nums[i-1]) i--; if (i!=0) { j=numssize-1; while (J>=i && nums[j]<=nums[i-1]) j--; TMP=NUMS[J]; NUMS[J]=NUMS[I-1]; nums[i-1]=tmp; } j=numssize-1; while (i<j) { tmp=nums[i]; NUMS[I]=NUMS[J]; nums[j]=tmp; i++;j--;} }
C + + source code (12MS):
Class Solution {public: void Nextpermutation (vector<int>& nums) { int j,len=nums.size (), i=len-1, TMP; while (i>0 && nums[i]<=nums[i-1]) i--; if (i>0) { j=len-1; while (J>=i && nums[j]<=nums[i-1]) j--; TMP=NUMS[I-1]; NUMS[I-1]=NUMS[J]; nums[j]=tmp; } j=len-1; while (i<j) { tmp=nums[i]; NUMS[I]=NUMS[J]; nums[j]=tmp; i++;j--;}} ;
Python source code (136MS):
Class solution: # @param {integer[]} nums # @return {void} do not return anything, modify Nums in-place instead.
def nextpermutation (Self, nums): Length=len (nums); i=length-1 while i>0 and Nums[i]<=nums[i-1]:i-=1 if i>0: j=length-1 while nums[j]<=nums[i-1]:j-=1 tmp=nums[j] nums[j]=nums[i-1] Nums[i-1]=tmp j=length-1 while i<j: tmp=nums[i] nums[i]=nums[j] nums[j]=tmp i+ =1;j-=1
Leetcode Next permutation (C,c++,java,python)