【LeetCode】C# 31、Next Permutation

来源:互联网 发布:网站在线下订单源码 编辑:程序博客网 时间:2024/06/09 04:21

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

也就是重新排列数组,使数组变成比原数大的最小的情况。
如果无法再大,就返回最小值。

思路:要实现上述条件
这里写图片描述
主要是思路不好想到。参考自http://www.cnblogs.com/etcow/archive/2012/10/02/2710083.html

public class Solution {    public void NextPermutation(int[] nums) {        if (nums.Length <= 1) return;            for (int i = nums.Length - 2; i >= 0; i--)            {                if (nums[i+1] > nums[i])                {                    //i++;                    for (int j = i+1; j < nums.Length; j++)                    {                        if (nums[j] <= nums[i])                        {                            if (j == i + 1)                            {                                int e = nums[nums.Length - 1];                                nums[nums.Length - 1] = nums[i];                                nums[i] = e;                                return;                            }                            int n = nums[j - 1];                            nums[j - 1] = nums[i];                            nums[i] = n;                            for (int k = i + 1, l = nums.Length - 1; k <= (nums.Length - i - 1) / 2 + i; k++, l--)                            {                                int t = nums[k];                                nums[k] = nums[l];                                nums[l] = t;                            }                            foreach (int item in nums)                                Console.WriteLine(item);                            return;                        }                    }                    int temp = nums[nums.Length - 1];                    nums[nums.Length - 1] = nums[i];                    nums[i] = temp;                    for (int k = i + 1, l = nums.Length - 1; k <= (nums.Length - i - 1) / 2 + i; k++, l--)                    {                        temp = nums[k];                        nums[k] = nums[l];                        nums[l] = temp;                    }                    foreach (int item in nums)                        Console.WriteLine(item);                    return;                }            }            for (int i = 0,j = nums.Length-1;i< nums.Length/2; i++,j--)            {                int m = nums[i];                nums[i] = nums[j];                nums[j] = m;            }    }}
原创粉丝点击