LeetCode31. Next Permutation最清晰的解法
2016-02-20 19:50
501 查看
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.
解答:
class Solution {
public:
void nextPermutation(vector<int>& nums) {
int pivot = findPivot(nums);
int sidx = findPivotSuccessor(nums, pivot);
if (pivot >= 0) {
std::swap(nums[pivot], nums[sidx]);
}
reverseSuffix(nums, pivot+1);
}
int findPivot(vector<int>& nums)
{
for (int i = nums.size()-2; i >= 0; i--) {
if (nums[i] < nums[i+1]) {
return i;
}
}
return -1;
}
int findPivotSuccessor(vector<int>&nums, int pivot)
{
int pv = nums[pivot];
int idx = -1;
for (int i = pivot+1; i < nums.size(); i++) {
if (nums[i] > pv) {
if (idx == -1) {
idx = i;
} else if (nums[idx] > nums[i]) {
idx = i;
}
}
}
return idx;
}
void reverseSuffix(vector<int>& nums, int start)
{
std::sort(nums.begin()+start, nums.end());
}
};
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
解答:
class Solution {
public:
void nextPermutation(vector<int>& nums) {
int pivot = findPivot(nums);
int sidx = findPivotSuccessor(nums, pivot);
if (pivot >= 0) {
std::swap(nums[pivot], nums[sidx]);
}
reverseSuffix(nums, pivot+1);
}
int findPivot(vector<int>& nums)
{
for (int i = nums.size()-2; i >= 0; i--) {
if (nums[i] < nums[i+1]) {
return i;
}
}
return -1;
}
int findPivotSuccessor(vector<int>&nums, int pivot)
{
int pv = nums[pivot];
int idx = -1;
for (int i = pivot+1; i < nums.size(); i++) {
if (nums[i] > pv) {
if (idx == -1) {
idx = i;
} else if (nums[idx] > nums[i]) {
idx = i;
}
}
}
return idx;
}
void reverseSuffix(vector<int>& nums, int start)
{
std::sort(nums.begin()+start, nums.end());
}
};
相关文章推荐
- ruby 数组使用教程
- Ruby中的数组和散列表的使用详解
- C#实现AddRange为数组添加多个元素的方法
- C#比较二个数组并找出相同或不同元素的方法
- C#动态调整数组大小的方法
- 详解Lua中的数组概念知识
- Perl中的列表和数组学习笔记
- 探索PowerShell (八) 数组、哈希表(附:复制粘贴技巧)
- C#中数组初始化与数组元素复制的方法
- C#交错数组用法实例
- Linux Shell 数组建立及使用技巧
- PowerShell数组的一些操作技巧
- C#通过yield实现数组全排列的方法
- C#不重复输出一个数组中所有元素的方法
- C#实现将数组内元素打乱顺序的方法
- C#中用foreach语句遍历数组及将数组作为参数的用法
- 详解C#编程中一维数组与多维数组的使用
- Ruby简明教程之数组和Hash介绍
- 深入解析C#中的交错数组与隐式类型的数组
- C语言查找数组里数字重复次数的方法