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

思路:

给定一个排列,按照字典序把下一个排列找出来。

Solution1:

code:

 /*
Time: O(n). We travese the given array
Space: O(1). We only used constant extra space.
*/ class Solution {
public void nextPermutation(int[] nums) {
// corner case
if (nums == null || nums.length == 0) return; int replace = nums.length - 2; //为何初始化为这个?因为下面要replace 和replace +1 比较
while (replace >= 0) {
if (nums[replace] < nums[replace + 1]) break;//从右往左扫
replace--;
}
if (replace < 0) {//说明数组总没有出现nums[replace]<nums[replace+1], 则数组为 654321 这种排序
Arrays.sort(nums); //返回题干说述的升序排列
return;
}
int lgrIdx = replace + 1;
//从nums[replace]往后,开始找剩下数字中,大于且最接近的nums[replace]的值
while (lgrIdx < nums.length && nums[lgrIdx] > nums[replace]) {
lgrIdx++;
}
int temp = nums[replace];
nums[replace] = nums[lgrIdx - 1];
nums[lgrIdx - 1] = temp;
Arrays.sort(nums, replace + 1, nums.length);
}
}

最新文章

  1. DEDE建站之图片标签技巧指南
  2. npm ERR publish 403,nodejs发布包流程
  3. redis中使用redis-dump导出、导入、还原数据实例
  4. Android -- 自定义带进度条的按钮
  5. Oracle命令:授权-收回权限-角色
  6. php 方便快捷导出excel
  7. Java-HTTP连接时如何使用代理(二)—— Proxy类方式
  8. 转:php中实现精确设置session过期时间的方法
  9. 基本RC积分电路及原理分析
  10. ubuntu 14.0 下github 配置
  11. iText 文本
  12. line-height:2、line-height:2em、line-height:200%的区别
  13. python测试断言
  14. invalidate和requestLayout
  15. 【PPT大放送】MPD软件工作坊北京站圆满落幕 深圳站即将开幕!
  16. Linux开启root用户
  17. (转载)Attempting to add QLayout &quot;&quot; to MainWindow &quot;&quot;, which already has a layout
  18. Eclipse中创建Maven项目失败
  19. C++ primer 第四版 练习3.13,3.14
  20. spring开发文档收集

热门文章

  1. Discuz! X3 全新安装图文教程
  2. java_oop_方法1
  3. Javascript 来判断数组的假值如 null false &quot;&quot; NaN
  4. 解决Android Studio在Ubuntu上出现“sdk/platform-tools/adb: error=2, No such file or directory”的方法
  5. oracle表被锁(delete或update一直处于执行状态)的处理办法。
  6. Python基础------运算符
  7. 前端-JavaScript1-6——JavaScript之变量类型的转换
  8. solr6.4.1搜索引擎(2)首次同步mysql数据库
  9. 3076: 神经网络(bfs和拓扑排序)
  10. Python中Lambda表达式使用