题目:

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

思路:

步骤如下:

  • 从最尾端开始往前寻找两个相邻的元素,两者满足i < ii(令第一个元素为i,第二个元素为ii)
  • 如果没有找到这样的一对元素则,表明当前的排列是最大的,没有下一个大的排列
  • 如果找到,再从末尾开始找出第一个大于i的元素,记为j                                  本文地址
  • 交换元素i, j,再将ii后面的所有元素颠倒排列(包括ii)
  • 如果某个排列没有比他大的下一个排列(即该排列是递减有序的),调用这个函数还是会把原排列翻转,即得到最小的排列
var nextPermutation = function(nums) {
var len=nums.length;
if(len<=1){
return;
} for(var i=len-2,j=len-1;i>=0;i--,j--){
if(nums[i]<nums[j]){
var q=len-1;
while(nums[q]<=nums[i]){
q--;
}
var temp=nums[i];
nums[i]=nums[q];
nums[q]=temp;
var a=nums.splice(q).reverse()
nums=nums.concat(a);
break;
}
}
if(i==-1){
nums.reverse();
}
};

最新文章

  1. 浅谈Oracle权限体系
  2. Python自动化之pickle和面向对象初级篇
  3. Python 写Windows Service服务程序
  4. c# 结构体、枚举类型及函数调用
  5. 对while((pid = waitpid(-1, &amp;stat, WNOHANG)) &gt; 0)不懂的地方,现在懂了
  6. 添加swap分区
  7. UVA 562 Dividing coins (01背包)
  8. Ajax随笔
  9. 网络爬虫-url索引
  10. python学习第二天:数字与字符串转换及逻辑值
  11. windows服务程序
  12. 在C#中使用CastleDynamicProxy 实现AOP
  13. 初学swift笔记 函数(六)
  14. 什么是TimeTunnel
  15. 【LCA求最近公共祖先+vector构图】Distance Queries
  16. 用VS Code体验调试.NET Core 2.0 Preview (传统三层架构)
  17. echarts3.0使用总结
  18. Kubernetes 笔记 05 yaml 配置文件详解
  19. 【GMT43智能液晶模块】例程十:DMA实验——存储器到存储器的传输
  20. SVN基本操作 (zz)

热门文章

  1. 文件读取ndarry 等价于DataFrame的操作
  2. B样条参数曲线学习(1)
  3. hdu4417(Super Mario)—— 二分+划分树
  4. WinRT 中后台任务类的声明
  5. FreeNas FTP配置
  6. VSTS 更名为 Azure DevOps
  7. Visual Studio模板
  8. DBCC--SHRINKDATABASE
  9. 设计模式之命令模式(Command Pattern)
  10. wpf ,只能窗口调整高度,并且设定最小值。