Next Permutation

来源:互联网 发布:质量数据分析管理办法 编辑:程序博客网 时间:2024/06/18 18:33

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,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1

思路就是从右往左扫,如果递增就继续,如果下一个数小于当前数num[cur],则再扫一遍找到比num[cur-1]大且比其他数小的下标。比如:1,3,4,2 搜到4 的时候发现下一个数字3比他小,那么就再从右往左扫一遍,找到比3大且比其他小的下标,这就是4的下标。调换num[cur-1] 和 num[minIndex],然后对剩下的右半边排列。

2014.11 update: 最后一步不要使用Arrays.sort,而是直接左右交换即可排序。

    public void nextPermutation(int[] num) {        int peakInd = 0;        for (int i = num.length-1; i > 0; i--) {            if (num[i] > num[i-1]) {                peakInd = i;                break;            }        }        if (peakInd > 0) {            int swapInd = num.length-1;            while (swapInd > peakInd-1 && num[swapInd] <= num[peakInd-1]) {                swapInd--;            }            int tmp = num[swapInd];            num[swapInd] = num[peakInd-1];            num[peakInd-1] = tmp;        }        int left = peakInd;        int right = num.length-1;        while (left < right) {            int tmp = num[left];            num[left] = num[right];            num[right] = tmp;            right--;            left++;        }    }


    public void nextPermutation(int[] num) {        int n = num.length;        if (n <= 1) {            return;        }        int cur = n-1;        while (cur >= 1 && num[cur-1]>= num[cur]) {            cur--;        }        if (cur == 0) {            Arrays.sort(num);            return;        }        int min = Integer.MAX_VALUE;        int minIndex = n-1;        for (int i = n-1; i >= cur; i--) {            if (num[i] > num[cur-1] && num[i] < min) {                min = num[i];                minIndex = i;            }        }        int tmp = num[cur-1];        num[cur-1] = num[minIndex];        num[minIndex] = tmp;        Arrays.sort(num, cur, n);    }


0 0
原创粉丝点击