【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
【解法】
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());//将替换后,关键点后的数据进行升序重排 } } };
相关文章推荐
- Go语言学习九:Map(集合)、递归函数、类型转换
- 使用magent搭建memcached集群
- yii2-GridView在开发中常用的功能及技巧
- yii使用网页
- -bash: crontab: command not found
- Github push掉坑纪录
- C# decimal类型(值类型、非基本类型)
- 数字信号处理与音频处理(使用Audition)
- tungsten抽取和应用mysql binlog
- php的查询数据
- vc2008对话框中mschart控件应用
- Odoo8.0根据资料的条件来控制画面上的修改、删除按钮显示
- C语言排序法(选择排序法/冒泡排序法)
- c++11 学习及测试(emplace_back实现方式 数学分布 正则表达式)
- React Native Android入门实战及深入源码分析系列(2)——React Native源码编译
- 批命令连接指定wifi 网络
- java多线程总结
- JavaScript parseInt() 函数
- C# 浮点类型(值类型)
- 场景内容的再现 - 天龙八部的源码分析(二)