My Java Solution


  • 0
    M

    public class NextPermutation
    {
    public void nextPermutation(int[] nums)
    {

    	if(nums.length <=1||null == nums)
    	{
    		return;
    	}
    	
    	int firstSwap = 0;
    	int secondSwap = 0;
    	
    	for(int i = nums.length - 2;i>=0;i--)
    	{
    		if(nums[i] >= nums[i + 1] )
    		{
    			continue;
    		}
    		else
    		{
    			firstSwap = i;
    			break;
    		}
    		
    	}
    	for(int i = nums.length - 1;i>firstSwap;i--)
    	{
    		if(nums[i] <= nums[firstSwap])
    		{
    			continue;
    		}
    		else
    		{
    			secondSwap = i;
    			break;
    		}
    		
    	}
    	if(firstSwap == 0&&secondSwap == 0)
    	{
    		reverse(nums,firstSwap,nums.length -1);
    		return;
    	}
    	
    	int temp = nums[firstSwap];
    	nums[firstSwap] = nums[secondSwap];
    	nums[secondSwap] = temp;
    	
    	reverse(nums,firstSwap + 1,nums.length -1);
    }
    
    private void reverse(int[] array,int start,int end)
    {
    	if(start >= end)
    	{
    		return;
    	}
    	while(end > start)
    	{
    		int temp = array[start];
    		array[start] = array[end];
    		array[end] = temp;
    		
    		end--;
    		start++;
    		
    	}
    	
    	
    	
    }
    

    }


Log in to reply
 

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