[LeetCode] 31. Next Permutation
来源:互联网 发布:mysql语句优化方法 编辑:程序博客网 时间:2024/06/16 13:19
https://leetcode.com/problems/next-permutation/#/solution
思路:
从右向左单向遍历,寻找第一个a[i-1] < a[i]的位置
然后从a[i]向后找,找到一个刚好大于a[i-1]的数a[j],交换a[i-1]<->a[j]
将a[i]到结尾逆序
写代码bug连连:
考虑
1 没有找到a[i-1],则全部逆序:
2 没有妥妥找到a[j](那就是后面最小的那个数)如 1 5 8 1 7 6 5 3 2
3 在找恰好大于a[i-1]的数,注意等于号 如1 5 1
class Solution {public: void nextPermutation(vector<int>& nums) { if (nums.size() == 0) return; int i = nums.size() - 1; int temp = 0; while (i >= 1) { if (nums[i-1] >= nums[i]) { i--; } else { break; } } if (i == 0) { reverse(nums.begin(), nums.end()); return; } else { int t = nums[i - 1]; int j; for (j = i; j < nums.size()-1; j++) { if (nums[j] > t && nums[j+1] <= t) { nums[i-1] = nums[j]; nums[j] = t; reverse(nums.begin() + i, nums.end()); return; } } nums[i-1] = nums[j]; nums[j] = t; reverse(nums.begin() + i, nums.end()); } }};
阅读全文
0 0
- [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
- 31. Next Permutation LeetCode
- 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
- Servlet实现文件上传,可多文件上传
- twelve
- Vector类在中间插入字符串
- 详细解析Raid0、Raid0+1、Raid1、Raid5四者的区别
- 数组习题及详解
- [LeetCode] 31. Next Permutation
- Codeforces Round #425 (Div. 2)
- oracle解决因drop命令生成临时表名的问题(如表分区)
- Java中CAS详解
- Android之UI学习篇:使用GridView实现九宫格的菜单
- 用单独js文件转thinkphp的U函数
- 协通xt800 anydesk teamview 密码获取
- 模拟用户登录
- form表单文件上传 servlet文件接收