31. Next Permutation

来源:互联网 发布:中山大学网络服务中心 编辑:程序博客网 时间:2024/06/16 22:53

题目

求下一个排序数
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,23,2,1 → 1,2,31,1,5 → 1,5,1

题目分析

看如下序列:

3 5 4 2 1

求其下一个排序数的思路:
1. 逆序搜索,找到第一个满足

nums[i1]<nums[i]
的位置,在 i=1 处。并且 i~n-1 序列一定是一个逆序序列
2. 交换 nums[i-1] 和 i>=1子序列的最小值。 最小值为 4;即交换 3 和 4,得到的序列为:4 5 3 2 1
3. 将i>=1的序列反转,即 4 1 2 3 5

代码

时间复杂度为O(n),空间复杂度为O(1)。

public class Solution {    public void NextPermutation(int[] nums) {        if(nums.Length<=1) return;        int i = findIndex(nums);        if(i==0)//no existence nums[i-1]<nums[i]            sortReverseNums(nums,0,nums.Length-1);        else {            int swap1 = findSwapIndex(nums,i);            swap(nums,i-1,swap1);            sortReverseNums(nums,i,nums.Length-1);        }    }    //find the first nums[i-1]<nums[i] of i    private int findIndex(int[] nums){        int n=nums.Length-1;        while(n>0){            if(nums[n-1]<nums[n])                break;            n--;        }        return n;    }    //find the swap index    //assert: i>=1    private int findSwapIndex(int[] nums, int i){        int n=nums.Length-1;        int swap1=nums[i-1];        int index;        for(index=n; index>=i;index--){            if(swap1<nums[index])                break;        }        return index;    }    private void swap(int[] nums, int i, int j){        int tmp=nums[i];        nums[i]=nums[j];        nums[j]=tmp;    }    private void sortReverseNums(int[] nums, int start, int end){        for(int i=start; i<=(start+end)/2;i++){            swap(nums,i,start+end-i);        }    }}