您的位置:首页 > 编程语言 > C#

【LeetCode】C# 31、Next Permutation

2017-10-10 23:26 555 查看
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;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode c#