您的位置:首页 > 其它

【LeetCode】31. Next Permutation解法

2016-03-31 10:44 309 查看
31. Next Permutation

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

【题目】

给定一个数据排列,要求找出该组数据组成的下一个比原排列大的数据,如果这样的数据不存在(原排列已经是最大组合),则将数据按升序排列(最小组合),说得更直白一点:给你三个数1,2,3,这三个数能够构成的最小数为123,最大为321,给定其中一种组合如132,要求下一个比它大的组合,必须是下一个,显然这个数为:213.

【分析】

这个题目本身不难,关键是理解题意,我们以一个例子来分析,给定325421,求其下一个比它大的数,怎么办呢?我们应该从最低位开始,1->2->4->5,这一段是升序的,也就是5421已经是最大数,不存在比它大的组合,我们继续找,1->2->4->5->2,出现降序这个位置就是我们要找的关键点,只需要将2与其后的数字中的(1,2,4,5)比它大的最小数,也就4替换,然后再将后面的数(1,2,2,5)升序排列便可得到下一个数,过程为:325421->345221->345122

【解法】

class Solution {
public:
void nextPermutation(vector<int>& nums)
{
int keyIndex=nums.size()-1;//指向最后一个数
while(keyIndex>0&&nums.at(keyIndex)<=nums.at(keyIndex-1))
keyIndex--;//寻找降序关键点

if(keyIndex==0)//如果关键点下标为0,则原数据排列为全降序,不存在比它更大的数,将原排列升序重排
{
sort(nums.begin(),nums.end())
}
else
{
int minNum=nums[keyIndex-1];//关键点下标对应的待替换数字
for(int i=nums.size()-1;i>keyIndex-1;i--)//寻找关键点后最小的且大于待替换数字的数据对应的下标
{
if(nums[i]>minNum)//找到,则替换
{
int temp;
temp=nums[i];
nums[i]=nums[keyIndex-1];
nums[keyIndex-1]=temp;
break;
}
}
sort(nums.begin()+keyIndex,nums.end());//将替换后,关键点后的数据进行升序重排
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: