[LeetCode] 31. 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,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1

 

解法:

  这道题要求下一个排列顺序,也就是全排列中的下一个(如:123的全排列为123、132、213、231、312、321,给定其中一个,输出其下一个),如果给定数组是降序,则说明是全排列的最后一种情况,则下一个排列就是最初始情况,全排列知识可以参见:全排列生成算法:next_permutation。我们再来看下面一个例子,有如下的一个数组

1  2  7  4  3  1

下一个排列为:

1  3  1  2  4  7

那么是如何得到的呢,我们通过观察原数组可以发现,如果从末尾往前看,数字逐渐变大,到了2时才减小的,然后我们再从后往前找第一个比2大的数字,是3,那么我们交换2和3,再把此时3后面的所有数字转置一下即可,步骤如下:

1  2  7  4  3  1

1  2  7  4  3  1

1  3  7  4  2  1

1  3  1  2  4  7

public class Solution {
    public void nextPermutation(int[] nums) {
        if (nums == null || nums.length == 0) {
            return;
        }
        int index = nums.length - 2;
        for (; index >= 0; index--) {
            if (nums[index] < nums[index + 1]) {
                break;
            }
        }
        if (index == -1) {
            Arrays.sort(nums);
            return;
        }
        
        int biggerIndex = nums.length - 1;
        for (; biggerIndex >= 0; biggerIndex--) {
            if (nums[biggerIndex] > nums[index]) {
                break;
            }
        }
        
        swap(nums, index, biggerIndex);
        reverse(nums, index + 1, nums.length - 1);
    }
    
    public void swap(int[] num, int i, int j) {
        int temp = num[i];
        num[i] = num[j];
        num[j] = temp;
    }
    
    public void reverse(int[] num, int begin, int end) {
        for (int i = begin, j = end; i < j; i++, j--) {
            swap(num, i, j);
        }
    }
}

 

posted @ 2017-02-21 15:08  Strugglion  阅读(236)  评论(0编辑  收藏  举报