C#LeetCode刷题之#31-下一个排列(Next Permutation)

问题

该文章已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/4965 访问。

实现获取下一个排列的函数,算法需要将给定数字序列重新排列成字典序中下一个更大的排列。

如果不存在下一个更大的排列,则将数字重新排列成最小的排列(即升序排列)。

必须原地修改,只允许使用额外常数空间。

以下是一些例子,输入位于左侧列,其相应输出位于右侧列。

1,2,3 → 1,3,2

3,2,1 → 1,2,3

1,1,5 → 1,5,1


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 and use only constant 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://www.byteflying.com/archives/4965 访问。

public class Program {

    public static void Main(string[] args) {
        var nums = new int[] { 1, 6, 9, 4, 2, 1 };

        NextPermutation(nums);
        ShowArray(nums);

        Console.ReadKey();
    }

    private static void ShowArray(int[] nums) {
        foreach(var num in nums) {
            Console.Write($"{num} ");
        }
        Console.WriteLine();
    }

    public static void NextPermutation(int[] nums) {
        var i = 0;
        var j = 0;
        var n = nums.Length;
        //从右往左找到第一个“逆行”的数字,此案例是 6,索引为 i
        //从右往左再找到第一个比“逆行数字”大的数字,此案例是 9
        //交换6、9,并将索引 i 之后的部分反转(原来为从大到小,改成从小到大)
        for(i = n - 2; i >= 0; i--) {
            if(nums[i + 1] > nums[i]) {
                for(j = n - 1; j >= i; j--) {
                    if(nums[j] > nums[i]) break;
                }
                var swap = nums[i];
                nums[i] = nums[j];
                nums[j] = swap;
                Array.Reverse(nums, i + 1, nums.Length - (i + 1));
                //可以返回了
                return;
            }
        }
        //如果已经是最大的了,直接反转成最小的
        Array.Reverse(nums, 0, nums.Length);
    }

}

以上给出1种算法实现,以下是这个案例的输出结果:

该文章已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/4965 访问。

1 9 1 2 4 6

分析

显而易见, 以上算法的时间复杂度为: O ( n 2 ) O(n^2)

猜你喜欢

转载自blog.csdn.net/qq_31116753/article/details/84189825