My java solution


  • 0
    C
     import java.util.*;
     public class Solution {
      public void nextPermutation(int[] nums) {	
    	
    	if(nums.length <=1)return;
    	
    	int first = -1;
    	int second = -1;
    	int target;
    	
    	for(int i=nums.length-2;i>=0;i--)
    	{
    		if(nums[i]<nums[i+1])
    		{
    			first = i;
    			second = i+1;
    			break;
    		}
    	}
    	
    	if(first == -1)
    	{
    		quicksort(nums,0,nums.length-1);
    		return;
    	}
    	
    	for(int j=nums.length-1;j>first;j--)
    	{
    		if(nums[j]>nums[first])
    		{
    			int tmp = nums[first];
    			nums[first] = nums[j];
    			nums[j] = tmp;
    			reverse(nums,second);
    			break;
    		}
    	
    	}
    	
    	
    }
    
    private void reverse(int[] nums, int i) {
    	// TODO Auto-generated method stub
    	quicksort(nums,i,nums.length-1);
    }
    
    private void quicksort(int[] nums, int i, int j) {
    	// TODO Auto-generated method stub
    	if(i<j)
    	{
    		int p = partition(nums,i,j);
    		quicksort(nums,i,p-1);
    		quicksort(nums,p+1,j);
    	}
    }
    
    private int partition(int[] nums, int i, int j) {
    	// TODO Auto-generated method stub
    	int r = i-1;
    	for(int k = i;k<j;k++)
    	{
    		if(nums[k]<nums[j])
    		{
    			r++;
    			int tmp = nums[r];
    			nums[r] = nums[k];
    			nums[k] = tmp;
    		}
    	}
    	r++;
    	int tmp = nums[r];
    	nums[r] = nums[j];
    	nums[j] = tmp;
    	return r;
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.