Wednesday, July 23, 2014

Next Permutation

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).
The replacement must be in-place, do not allocate extra memory.

Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,31,3,2
3,2,11,2,3
1,1,51,5,1

从末尾开始找到第一个降序的地方,记录降序地方小的那个值,继续从末尾开始找到第一个比那个值大的数,两者交换,然后把从末尾到降序的部分反转。
注意有可能整个数组从末尾都是升序的情况。
public class Solution {
    //Time: O(n)  Space: O(1)
    public void nextPermutation(int[] num) {
        if (num == null || num.length == 0) {
            return;
        }
        
        int i = num.length - 1;
        for (; i > 0; i--) {
            if (num[i] > num[i - 1]) {
                break;
            }
        }
        if(i == 0) {
            reverse(num, 0);
            return;
        }
        
        int j = num.length - 1;
        for (; j >= 0; j--) {
            if (num[j] > num[i - 1]) {
                break;
            }
        }
        
        int temp = num[i - 1];
        num[i - 1] = num[j];
        num[j] = temp;
        reverse(num, i);
    }
    
    private void reverse(int[] num, int index) {
        int left = index;
        int right = num.length - 1;
        while (left < right) {
            int temp = num[left];
            num[left] = num[right];
            num[right] = temp;
            left++;
            right--;
        }
    } 
}

No comments:

Post a Comment