【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
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 刷题之路 31 Triangle
- [leetcode] 31. Next Permutation
- leetcode 31 - next permutation
- LeetCode_31---Next Permutation
- [LeetCode]--31. Next Permutation
- leetcode 31: Minimum Depth of Binary Tree
- LeetCode 31
- [leetcode] 31. Next Permutation 解题报告
- LeetCode - 31. Next Permutation
- LeetCode 31. Next Permutation
- leetcode[31]Next Permutation
- leetcode problem 31 -- Next Permutation
- [LeetCode]31. Best Time to Buy and Sell Stock股票买卖
- leetcode (31) Next Permutation
- [leetcode] 31. Next Permutation
- leetcode 31: Minimum Depth of Binary Tree
- LeetCode Weekly Contest 31解题思路
- 31. Next Permutation LeetCode
- <LeetCode OJ>Next Permutation【31】
- Leetcode-31. Next Permutation