#52 Next Permutation
来源:互联网 发布:中国家暴数据 编辑:程序博客网 时间:2024/04/30 15:29
题目描述:
Given a list of integers, which denote a permutation.
Find the next permutation in ascending order.
Notice
The list may contains duplicate integers.
Example
题目思路:For [1,3,2,3]
, the next permutation is [1,3,3,2]
For [4,3,2,1]
, the next permutation is [1,2,3,4]
这题注意到,正常的规律从后到前应该是后一个数比前一个数大。如果发现前一个数更小时,这就是发生转折点的地方。首先,我们先找到这个转折点(如果找不到,那么答案就是reversed array);然后从转折点往后看,找出大于转折点的最小数,并把这个数和转折点互换。对于新转折点后那些剩下的数,做一个sort。这样,改完的数组就是答案了。
Mycode(AC = 32ms):
class Solution {public: /** * @param nums: An array of integers * @return: An array of integers that's next permuation */ vector<int> nextPermutation(vector<int> &nums) { // write your code here if (nums.size() <= 1) return nums; // find the key position int idx = -1; for (int i = nums.size() - 2; i >= 0; i--) { if (nums[i] < nums[i + 1]) { idx = i; break; } } // if is the larget sequence, return reverse if (idx == -1) { reverse(nums.begin(), nums.end()); return nums; } int second_min = nums[idx + 1], second_idx = idx + 1; for (int i = idx + 1; i < nums.size(); i++) { if (nums[i] > nums[idx] && nums[i] < second_min) { second_min = nums[i]; second_idx = i; } } // swap swap(nums, idx, second_idx); // sort the rest numbers sort(nums.begin() + idx + 1, nums.end()); return nums; } void swap(vector<int> &nums, int i, int j) { int tmp = nums[i]; nums[i] = nums[j]; nums[j] = tmp; }};
0 0
- #52 Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- Next Permutation
- [欧拉序列 LCA 鬼畜暴枚] BZOJ 1906 树上的蚂蚁 && BZOJ 3700 发展城市
- Maven私服搭建
- static用法小结
- 周易六十四卦——蹇卦
- 从无到有——制作简易编译器(一)
- #52 Next Permutation
- 装饰者模式
- Matlab调用OpenCV(C++)程序
- Servlet学习笔记---防止表单重复提交
- Build WebRTC for Android
- 15个不起眼但非常强大的 Vim 命令
- 学习记录:安装binwalk
- 解决RedHat中ifconfig命令不能使用的问题
- 大神谁来帮帮我