lintcode-medium-Next Permutation

---恢复内容开始---

Given a list of integers, which denote a permutation.

Find the next permutation in ascending order.

 

Notice

The list may contains duplicate integers.

Example

For [1,3,2,3], the next permutation is [1,3,3,2]

For [4,3,2,1], the next permutation is [1,2,3,4]

 

public class Solution {
    /**
     * @param nums: an array of integers
     * @return: return nothing (void), do not return anything, modify nums in-place instead
     */
    public int[] nextPermutation(int[] nums) {
        // write your code here
        
        if(nums == null || nums.length <= 1)
            return nums;
        
        int i = nums.length - 1;
        
        while(i > 0 && nums[i - 1] >= nums[i])
            i--;
        
        if(i == 0){
            reverse(nums, 0, nums.length - 1);
            return nums;
        }
        
        i--;
        
        int j = i + 1;
        
        while(j < nums.length && nums[j] > nums[i])
            j++;
        
        j--;
        
        swap(nums, i, j);
        reverse(nums, i + 1, nums.length - 1);
        
        return nums;
    }
    
    public void swap(int[] nums, int i, int j){
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
        
        return;
    }
    
    public void reverse(int[] nums, int start, int end){
        while(start < end){
            swap(nums, start, end);
            start++;
            end--;
        }
        
        return;
    }
    
}

 

posted @ 2016-04-02 06:29  哥布林工程师  阅读(115)  评论(0编辑  收藏  举报