【LeetCode】31. Next Permutation
来源:互联网 发布:大数据access和mysql 编辑:程序博客网 时间:2024/06/07 04:43
题目描述
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,23,2,1 → 1,2,31,1,5 → 1,5,1
解题思路
因为要找的是比当前排列大一点的下一个排列,所以应该通过调整最靠后面的数字的排序来实现。
从后往前找,如果数字一直增大,那是没有办法通过调整后面的排列来得到更大的排列的。
当找到一个数字,它比后一个数字小时,才可以开始实行交换。将那个数字与已经遍历过的部分中恰好比它大一点的值进行交换,然后反转后半部分,即让它由从后往前的递增变为递减。
AC代码
class Solution {public: void nextPermutation(vector<int>& nums) { if (nums.size() < 2) return; int startIdx = nums.size() - 2; while (startIdx >= 0) { if (nums[startIdx] >= nums[startIdx + 1]) { startIdx--; } else { //get the upper bound int upperIdx = nums.size() - 1; for (; upperIdx > startIdx; --upperIdx) { if (nums[upperIdx] > nums[startIdx]) break; } //swap and break int temp = nums[startIdx]; nums[startIdx] = nums[upperIdx]; nums[upperIdx] = temp; break; } } sort(nums.begin() + startIdx + 1, 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
- Linux解压文件
- js为Object对象动态添加属性和值
- iframe刷新
- 【caffe-Windows】新层添加——LSTM
- 向量的点乘与叉乘的几何意义
- 【LeetCode】31. Next Permutation
- 【面试题】剑指offer 6
- sublime标题栏存在中文乱码
- 1099. Build A Binary Search Tree (30)
- drupal capture can not open
- CodeVS2873 日程表安排
- [LeetCode]412. Fizz Buzz
- 初级程序员 需求分析那点事(一)
- Android7.0新特性,及Android N适配