leetcode题集——next-permutation
2016-07-19 17:35
197 查看
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
字典序排列。理解题意万岁!!!
大致分为三个步骤:
假设vector<int> num有len个元素,
STEP 1:从右(len-1)向左(i)遍历,找到num[i]>num[i-1]。如果没有,则i==0,将num从小到大排序,作为返回值。
STEP 2:同样地,从右(len-1)向左(i)遍历,找到从最右边开始,第一个比num[i-1]大的元素下标minindex。并交换num[i-1]与num[minindex]。
STEP 3:将新的num[i]到num[len-1]从小到大排序。
class Solution {
public:
void swap(int &a,int &b)
{
int tem=a;
a=b;
b=tem;
}
void nextPermutation(vector<int> &num)
{
int len=num.size();
int i;
for(i=len-1;i>0;i--)
{
if(num[i-1]<num[i])
break;
}
//当排列的所有元素递减时,表示最大值。返回最小值
if(i==0)
{
std::sort(num.begin(),num.end());
return;
}
int minindex=i;
for(int j=len-1;j>=i;j--)
{
if(num[j]>num[i-1])
{
minindex=j;
break;
}
}
swap(num[i-1],num[minindex]);
std::sort(num.begin()+i,num.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
字典序排列。理解题意万岁!!!
大致分为三个步骤:
假设vector<int> num有len个元素,
STEP 1:从右(len-1)向左(i)遍历,找到num[i]>num[i-1]。如果没有,则i==0,将num从小到大排序,作为返回值。
STEP 2:同样地,从右(len-1)向左(i)遍历,找到从最右边开始,第一个比num[i-1]大的元素下标minindex。并交换num[i-1]与num[minindex]。
STEP 3:将新的num[i]到num[len-1]从小到大排序。
class Solution {
public:
void swap(int &a,int &b)
{
int tem=a;
a=b;
b=tem;
}
void nextPermutation(vector<int> &num)
{
int len=num.size();
int i;
for(i=len-1;i>0;i--)
{
if(num[i-1]<num[i])
break;
}
//当排列的所有元素递减时,表示最大值。返回最小值
if(i==0)
{
std::sort(num.begin(),num.end());
return;
}
int minindex=i;
for(int j=len-1;j>=i;j--)
{
if(num[j]>num[i-1])
{
minindex=j;
break;
}
}
swap(num[i-1],num[minindex]);
std::sort(num.begin()+i,num.end());
}
};
相关文章推荐
- Python 模块学习:os模块
- mysql 5.6.30 开启慢查询日志
- iOS: #ifdef DEBUG
- W3C对DOM2.0定义的标准事件
- 使用ShareSDK分享到新浪微博遇到的一些问题
- 给RecyclerView通用Adapter添加Item单击事件
- 剑指offer----求1+2+3+...+n----java实现
- 5个让你充满健身动力的方法
- Android RocooFix 热修复框架[1]
- 220. Contains Duplicate III
- 利用java基础写的一个简单的小游戏,没有UI界面,只是涉及到类的封装,方法的调用,方便日后复习用
- 【Cocos】系统内置事件
- SpringMVC学习(一)
- java冒泡排序和快速排序的实现
- 星际SC 地图 Big Game Fort 要塞之战 修正了 BIG GAME 地图的平衡性
- 模拟地与数字地详解
- Linux进程管理(三、 线程)
- U盘文件消失没有被隐藏却占内存的几种解决方案
- C#中的webBrowser控件加载网页时实现进度显示
- 六个增肌小技巧 让肌肉得到意想不到的刺激