[抄题]:

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

[暴力解法]:

时间分析:

空间分析:

[优化后]:

时间分析:

空间分析:

[奇葩输出条件]:

[奇葩corner case]:

[思维问题]:

完全不知道怎么操作啊:从后往前找递增,再把递减的尾巴整个reverse一遍,变成递增。

[英文数据结构或算法,为什么不用别的数据结构或算法]:

[一句话思路]:

把递减的尾巴整个reverse一遍,变成递增。i和后面交换,确保更加递增。

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

[一刷]:

从合理性的角度考虑:reverse(nums, i + 1, len - 1); 则i可以从-1开始。

[二刷]:

[三刷]:

[四刷]:

[五刷]:

[五分钟肉眼debug的结果]:

[总结]:

把递减的尾巴整个reverse一遍,变成递增。i和后面交换,确保更加递增。

[复杂度]:Time complexity: O(n) Space complexity: O(1)

[算法思想:迭代/递归/分治/贪心]:

[关键模板化代码]:

[其他解法]:

[Follow Up]:

[LC给出的题目变变变]:

[代码风格] :

[是否头一次写此类driver funcion的代码] :

[潜台词] :

class Solution {
public void nextPermutation(int[] nums) {
int len = nums.length; //corner case
if (nums == null || len < 2) return ; //find the first ascending i from len - 2
int i = len - 2;
while (i >= 0 && nums[i] >= nums[i + 1]) i--; if (i >= 0) {
//find the max j from the len - 1
int j = len - 1;
while (nums[i] >= nums[j]) j--; //swap i & j
swap(nums, i, j);
}
//reverse from i+1 to len - 1
reverse(nums, i + 1, len - 1);
System.out.println("i = " + i);
} public void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
} public void reverse(int[] nums, int i, int j) {
while (i < j)
swap(nums, i++, j--);
}
}

最新文章

  1. 图像缩放_OpenCv
  2. Win10上使用SVN遇到的一些问题
  3. 细数.NET 中那些ORM框架 —— 谈谈这些天的收获之一
  4. Python控制语句
  5. Neutron分析(3)—— neutron-l3-agent
  6. 移动web设计稿尺寸,关于移动web尺寸的那点事
  7. List的输出方法
  8. mysql view视图的简单使用....
  9. VBS windows监控
  10. [USACO13NOV]没有找零No Change [TPLY]
  11. Unity3D项目程序加密-VirboxProtector加壳工具
  12. [AtCoder agc021D]Reversed LCS
  13. UVa - 102 - Ecological Bin Packing
  14. ES进阶--04
  15. bzoj千题计划315:bzoj3172: [Tjoi2013]单词(AC自动机)
  16. prufer编码
  17. 权限控制框架---shiro入门
  18. ccf题库20170903--Json查询
  19. C#_Math函数总结
  20. MindManager篇

热门文章

  1. SUID、SGID、粘滞位
  2. Docker概念(二)
  3. node 下less无法编译的问题
  4. 如何用原生js开发一个Chrome扩展程序
  5. ByteToByte64String、Base64StringToBytes
  6. MySQL数据库中统计一个库中的所有表的行数?
  7. [蓝桥杯]ALGO-187.算法训练_P0502
  8. Python 面向对象(三)
  9. 第三章 FFmpeg转封装
  10. (2) linux文件系统简介