码迷,mamicode.com
首页 > 其他好文 > 详细

lintcode-medium-Next Permutation II

时间:2016-04-02 07:07:00      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:

Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.

If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).

 

Example

Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.

1,2,3 → 1,3,2

3,2,1 → 1,2,3

1,1,5 → 1,5,1

Challenge

The replacement must be in-place, do not allocate extra memory.

 

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

 

lintcode-medium-Next Permutation II

标签:

原文地址:http://www.cnblogs.com/goblinengineer/p/5346857.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!