leetcode 31. Next Permutation
2016-03-31 23:05
295 查看
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) {
if (nums.size() < 2)
return ;
vector<int>aa = nums;
sort(aa.begin(), aa.end());
int k = nums.size()-1;
while (k >= 1)
{
vector<int>cc; cc.push_back(nums[k]);
while (k >= 1 && nums[k] <= nums[k - 1])
{
cc.push_back(nums[k - 1]);
k--;
}
if (k == 0)
{
nums = aa;
return;
}
cc.push_back(nums[k - 1]);
sort(cc.begin(), cc.end());
for (int i = 0; i < cc.size();i++)
if (cc[i] > nums[k - 1])
{
nums[k - 1] = cc[i];
cc.erase(cc.begin() + i, cc.begin() + i + 1);
for (int j = 0; j < cc.size(); j++)
nums[k + j] = cc[j];
return;
}
}
}
};
accepted
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) {
if (nums.size() < 2)
return ;
vector<int>aa = nums;
sort(aa.begin(), aa.end());
int k = nums.size()-1;
while (k >= 1)
{
vector<int>cc; cc.push_back(nums[k]);
while (k >= 1 && nums[k] <= nums[k - 1])
{
cc.push_back(nums[k - 1]);
k--;
}
if (k == 0)
{
nums = aa;
return;
}
cc.push_back(nums[k - 1]);
sort(cc.begin(), cc.end());
for (int i = 0; i < cc.size();i++)
if (cc[i] > nums[k - 1])
{
nums[k - 1] = cc[i];
cc.erase(cc.begin() + i, cc.begin() + i + 1);
for (int j = 0; j < cc.size(); j++)
nums[k + j] = cc[j];
return;
}
}
}
};
accepted
相关文章推荐
- ubuntu server 改变phpmyadmin的默认访问路径
- DTS、杜比2.0、杜比5.1、AC3各是什么意思
- Add Two Numbers(OC版)
- 浅谈栈帧(一)
- ListView优化之图片的三级缓存(LruCache)
- IOS UIScrollView——用法详解
- LinearLayout, FrameLayout,RelativeLayout 布局案例
- 牛客网每日打卡-Java基础-20160331
- DRY
- 每天一篇python:时间日期篇
- 【Codeforces659D】Bicycle Race【向量叉积】
- DatePickerDialog日期选择器的使用
- 仿百度壁纸客户端(二)——主页自定义ViewPager广告定时轮播图
- 快速排序
- 仿百度壁纸客户端(二)——主页自定义ViewPager广告定时轮播图
- jar7
- for 循环嵌套 while 的神奇问题
- leetcode_147 Insertion Sort List
- 浅谈css背景
- Android 中Fragment与Activity通信大汇总