【LeetCode】31. Next Permutation
2018-04-09 22:58
357 查看
题目描述
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
解题思路
因为要找的是比当前排列大一点的下一个排列,所以应该通过调整最靠后面的数字的排序来实现。从后往前找,如果数字一直增大,那是没有办法通过调整后面的排列来得到更大的排列的。
当找到一个数字,它比后一个数字小时,才可以开始实行交换。将那个数字与已经遍历过的部分中恰好比它大一点的值进行交换,然后反转后半部分,即让它由从后往前的递增变为递减。
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()); } };
相关文章推荐
- leetcode_31题——Next Permutation(STL)
- [LeetCode]31. Best Time to Buy and Sell Stock股票买卖
- LeetCode - Single number- Jan 31, 2015
- LeetCode Weekly Contest 31解题思路
- leetcode[31]Next Permutation
- leetcode 31. Next Permutation
- [LeetCode]31. Next Permutation
- LeetCode 31 Next Permutation 寻找一个数字序列的比他大的最小序列
- 【leetcode】31. Next Permutation
- [LeetCode] Subsets [31]
- <LeetCode OJ>Next Permutation【31】
- 【一天一道LeetCode】#31. Next Permutation
- leetcode - 31.Next Permutation
- Leetcode-31: 31. Next Permutation
- Leetcode 31 Next Permutation
- LeetCode(31) Next Permutation
- LeetCode[31] Next Permutation 求下一个排列
- [LeetCode]Array主题系列{1,11,15,16,18,26,27,31,33,34题}
- leetcode编程记录16 #31 Next Permutation
- leetcode 31. Next Permutation