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

[leetcode] Next Permutation

时间:2014-06-27 12:14:44      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:class   blog   code   java   http   tar   

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

https://oj.leetcode.com/submissions/detail/2805266/

思路:如下图。

bubuko.com,布布扣

 

代码实现:

import java.util.Arrays;

public class Solution {
    public void nextPermutation(int[] num) {
        if (num == null || num.length <= 1)
            return;

        int n = num.length;
        int partitionIdx = -1;
        for (int i = n - 1; i > 0; i--) {
            if (num[i - 1] < num[i]) {
                partitionIdx = i - 1;
                break;
            }
        }
        int tmp;
        if (partitionIdx == -1) {
            for (int i = 0, j = n - 1; i < j; i++, j--) {
                tmp = num[i];
                num[i] = num[j];
                num[j] = tmp;
            }

        } else {
            int changeNumIdx = -1;
            for (int i = n - 1; i > partitionIdx; i--) {
                if (num[i] > num[partitionIdx]) {
                    changeNumIdx = i;
                    break;
                }
            }
            tmp = num[partitionIdx];
            num[partitionIdx] = num[changeNumIdx];
            num[changeNumIdx] = tmp;

            for (int i = partitionIdx + 1, j = n - 1; i < j; i++, j--) {
                tmp = num[i];
                num[i] = num[j];
                num[j] = tmp;

            }

        }

    }

    public static void main(String[] args) {
        int[] num;
        num = new int[] { 1, 2, 3, 5, 4, 4, 1 };
        new Solution().nextPermutation(num);
        System.out.println(Arrays.toString(num));

        num = new int[] { 1, 1, 5 };
        new Solution().nextPermutation(num);
        System.out.println(Arrays.toString(num));

        num = new int[] { 3, 2, 1 };
        new Solution().nextPermutation(num);
        System.out.println(Arrays.toString(num));

        num = new int[] { 1, 1 };
        new Solution().nextPermutation(num);
        System.out.println(Arrays.toString(num));

    }

}

参考:

http://fisherlei.blogspot.com/2012/12/leetcode-next-permutation.html

扩展:

http://blog.csdn.net/m6830098/article/details/17291259

 

 

[leetcode] Next Permutation,布布扣,bubuko.com

[leetcode] Next Permutation

标签:class   blog   code   java   http   tar   

原文地址:http://www.cnblogs.com/jdflyfly/p/3810727.html

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