31. Next Permutation | Java最短代码实现
来源:互联网 发布:foxmail国外端口设置 编辑:程序博客网 时间:2024/04/28 04:56
原题链接:31. Next Permutation
欢迎优化!
【思路】
首先,我们来了解一下——字典序法:
C++的STL库里面有nextPermutation()方法,其实现就是字典序法。
下图简单明了地介绍了字典序法
例如,1234的全排列如下:
简单归纳,从右边开始,找到第一个正序数 nums[i] ,然后从右边找第一个大于 num[i] 的数 nums[j](j > i),找到之后交换 nums[i] 和 nums[j] ,最后将 nums[i + 1] 至 nums[nums.length - 1]之间的数进行反转:
public void nextPermutation(int[] nums) { for (int i = nums.length - 2; i >= 0; i--) if (nums[i] < nums[i + 1]) for (int j = nums.length - 1; j > i; j--) if (nums[i] < nums[j]) { swap(nums, i, j); reverse(nums, i + 1, nums.length - 1); return; } reverse(nums, 0, nums.length - 1); } private void swap(int[] nums, int left, int right) { int temp = nums[left]; nums[left] = nums[right]; nums[right] = temp; } private void reverse(int[] nums, int left, int right) { while (left < right) swap(nums, left++, right--); }265 / 265 test cases passed. Runtime: 2 ms Your runtime beats 9.15% of javasubmissions.
欢迎优化!
1 0
- 31. Next Permutation | Java最短代码实现
- 60. Permutation Sequence | Java最短代码实现
- [leetcode]31.Next Permutation(Java实现)
- leetcode-java-31. Next Permutation
- (Java)LeetCode-31. Next Permutation
- [LeetCode-Java]31. Next Permutation
- [LeetCode] 31. Next Permutation java
- Rotate List | Java最短代码实现
- 3Sum | Java最短代码实现
- H-Index | Java最短代码实现
- Jump Game | Java最短代码实现
- Leetcode 31. Next Permutation (Medium) (java)
- Leetcode#31. Next Permutation(java)
- [Leetcode] Next Permutation (Java)
- Next Permutation (Java)
- [LeetCode][Java] Next Permutation
- LeetCode : Next Permutation [java]
- leetcode 79. Word Search | Java最短代码实现
- ios学习--照片框架详解
- 计算机基础 vb练习
- solution Of Pat 1114. Family Property (25)
- 迁移ESX虚拟机到KVM
- Android 应用程序的图标 (Icon)需要准备的四个尺寸
- 31. Next Permutation | Java最短代码实现
- LeetCode Algorithms #101 <Symmetric Tree>
- hdu 3954(线段树区间更新)
- 从准备考研到复试结束的日子里的一些感慨
- odoo中的QWeb模板引擎
- Spring @Value注解使用${}进行注入
- couldn't find file 'jquery.ui.effect-blind' with type 'application/javascript'
- 项目遇到的问题汇总<一>之下拉菜单所有问题
- swift约束之SnapKit的使用方式