Level:

  Medium

题目描述:

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 and use only constant 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

思路分析:

  这道题要求是给出当前序列的下一个序列(当前序列的下一个更大的序列),意思就是求当前序列的下一个字典序列。那么我们有以下算法:

  给定一个序列假如是a1,a2,a3,..ai,ai+1,ai+2..,aj..an

  1.找到最后一个正序序列ai,ai+1;

  2.找到ai后面最后一个比他大的数aj;

  3.交换ai和aj; a1,a2,a3,..aj,ai+1,ai+2..,ai..an

  4.将aj后面的所有数反转,即得到下一个序列,即下一个比它大的数

代码:

public class Solution{
public void nextPermutation(int []nums){
if(nums==null||nums.length==0)
return;
//第一步找到最后一对正序序列
int flag=-1;
for(int i=nums.length-1;i>=1;i--){
if(nums[i]>nums[i-1]){
flag=i-1;
break;
}
}
// 如果不存在正序,则证明该序列是由大到小的逆序,则反转整个序列
if(flag==-1){
reverse(nums,flag+1,nums.length-1);
return;
}
//如果存在正序,则找到flag后面最后一个比它大的数,并交换
for(int j=nums.length-1;j>flag;j--){
if(nums[j]>nums[flag]){
int temp=nums[j];
nums[j]=nums[flag];
nums[flag]=temp;
break;
}
}
//反转flag位置后的序列
reverse(nums,flag+1,nums.length-1);
return ;
}
public void reverse(int []nums,int start,int end){//反转序列
while(start<end){
int temp=nums[end];
nums[end]=nums[start];
nums[start]=temp;
start++;
end--;
}
}
}

最新文章

  1. Linux修改环境变量的方法
  2. HTML Meta标签
  3. [Shell]Bash变量:变量测试与内容替换
  4. 如何将list转为json?
  5. 一些判断Linux是否被黑的经验
  6. GUI图形界面
  7. URAL 1776 C - Anniversary Firework DP
  8. dedecms 常用标签
  9. Because the people who are crazy enough to think they can change the world, are the ones who do.
  10. Eclipse代码风格设置
  11. android部分控件应用解析
  12. js提交表单错误:document.form.submit() is not a function
  13. Java IO编程全解(一)——Java的I/O演进之路
  14. 常见优化算法统一框架下的实现:最速下降法,partan加速的最速下降法,共轭梯度法,牛顿法,拟牛顿法,黄金分割法,二次插值法
  15. 【Android Studio安装部署系列】十八、Android studio更换APP应用图标
  16. cuda培训素材
  17. Java学习——集合框架【4】
  18. CC2530 Debug ---CC2530 无启动之32K晶振
  19. (转)60s快速分析Linux性能
  20. MySQL分区管理

热门文章

  1. Openssl ec命令
  2. pcl文档库
  3. TF Boys (TensorFlow Boys ) 养成记(四):TensorFlow 简易 CIFAR10 分类网络
  4. Python2.7.9 编码问题
  5. Session分布式共享 = Session + Redis + Nginx(转)
  6. osgQt支持触摸屏
  7. 编写高质量代码改善C#程序的157个建议——建议142:总是提供有意义的命名
  8. Head First Python之4持久存储
  9. Selenium2+python自动化之数据驱动(ddt)
  10. easyui datagrid单元格实现溢出文本显示省略号的效果。