【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; } }}
阅读全文
0 0
- 【LeetCode】C# 31、Next Permutation
- LeetCode 31: Next Permutation
- [leetcode 31] Next Permutation
- LeetCode(31) Next Permutation
- LeetCode---(31) Next Permutation
- leetcode 31 -- Next Permutation
- leetcode 31: Next Permutation
- LeetCode(31) Next Permutation
- LeetCode-31 Next Permutation
- Leetcode#31||Next Permutation
- LeetCode 31: Next Permutation
- LeetCode(31)-Next Permutation
- leetcode(31) Next Permutation
- LeetCode 31 - Next Permutation
- 【leetcode】【31】Next Permutation
- LeetCode-31:Next Permutation
- leetcode (31) Next Permutation
- LeetCode 31 Next Permutation
- 表、栈、队列
- [leetCode 解题报告]026. Remove Duplicates from Sorted Array
- jquery中的定时刷新
- ios app 加载完启动图时黑屏一秒钟
- 大学四年如何成为优秀的ACM大牛
- 【LeetCode】C# 31、Next Permutation
- 设计模式之----单例模式
- 在html文档/指定标签中输出时间
- libevent源码学习-----事件驱动流程分析
- *【bzoj 1355】Radio Transmission(kmp)
- 每天一个linux命令(5):rm 命令
- PTA 7-7(排序) Windows消息队列(25 分) 25分代码 优先队列
- Java——线程间通信 常用方法
- php使用phantomjs生成pdf