lintcode52- Next Permutation- medium

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]

这题主要是要了解好找下一个排列的方法,利用规则:如果一个序列是递减的,那么它不具有下一个排列。算法实现还好。

算法:数学算法。看着 13248653   1.从后向前找到最靠后的一对增序对prev,next,此处48。 2.在next~最后中从后找到第一个比prev大的数字biggerNum。 3.交换biggerNum 4.排序现在后面的部分next~最后。

细节:1.本题最后要排序列部分是有序的,这里只要做逆序就好,不用做sort,时间复杂度好点。 2.注意一个corner case:就是一开始就全逆序的,找不到最后一对增序对,实际上循环来做需要输出第一个全增排列。

public class Solution {
    /**
     * @param num: an array of integers
     * @return: return nothing (void), do not return anything, modify num in-place instead
     */
     
    public void reverse(int[] num, int start, int end) {
        for (int i = start, j = end; i < j; i++, j--) {
            int temp = num[i];
            num[i] = num[j];
            num[j] = temp;
        }
    }
    
    public int[] nextPermutation(int[] num) {
        // find the last increase index
        int index = -1;
        for (int i = num.length - 2; i >= 0; i--) {
            if (num[i] < num[i + 1]) {
                index = i;
                break;
            }
        }
        if (index == -1) {
            reverse(num, 0, num.length - 1);
            return num;
        }
        
        // find the first bigger one
        int biggerIndex = index + 1;
        for (int i = num.length - 1; i > index; i--) {
            if (num[i] > num[index]) {
                biggerIndex = i;
                break;
            }
        }
        
        // swap them to make the permutation bigger
        int temp = num[index];
        num[index] = num[biggerIndex];
        num[biggerIndex] = temp;
        
        // reverse the last part
        reverse(num, index + 1, num.length - 1);
        return num;
    }
}
原文地址:https://www.cnblogs.com/jasminemzy/p/7782133.html