leetcode 31. Next Permutation
来源:互联网 发布:linux创建文件的api 编辑:程序博客网 时间:2024/06/07 03:39
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
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
思路:i从后往前,在i后面找比i位大的最小值,交换i和找到那个位置的值,然后在i后面的排个序!
class Solution {public: void nextPermutation(vector<int>& nums) { if (nums.size() < 2) return; int swap_pos; int swap_value; for (int i = nums.size() - 2; i >= 0; i--) { swap_value = INT_MAX; for (int j = i + 1; j <= nums.size() - 1 ; j++) { if (nums[i] < nums[j] && nums[j] < swap_value) { swap_value = nums[j]; swap_pos = j; } } if (swap_value != INT_MAX) { swap(nums[i], nums[swap_pos]); sort(nums.begin() + i + 1, nums.end()); return; } } sort(nums.begin(), nums.end()); return; }};
阅读全文
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
- 近200篇机器学习&深度学习资料分享(含各种文档,视频,源码等)
- QGis二次开发基础 -- 构建图层管理器
- PHP开发APP接口(二)
- sonar 输出日志分析
- jQueryUI 日历
- leetcode 31. Next Permutation
- android popupwindow在屏幕内水平居中
- 7000个传感器遍布街道 控江路街道完成社区物联网工程第一期建设
- iOS 11开发教程(七)编写第一个iOS11代码Hello,World
- Java堆内存和栈内存分析
- HttpClient POST传参, SpringMVC接受
- 安装docker私有镜像库及简易管理工具
- CentOS 配置MySQL允许远程登录
- eclipse Ctrl +左键查看源代码提示找不到源source not found