Leetcode-31. Next Permutation
来源:互联网 发布:char占几个字节 java 编辑:程序博客网 时间:2024/06/14 14:17
前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN,mcf171专栏。
博客链接:mcf171的博客
——————————————————————————————
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
比如输入是6 5 4 8 7 5 1
首先肯定从后面开始看,1和5调换了没有用。7、5和1调换了也没有效果,因此而发现了8、7、5、1是递减的。如果想要找到下一个排列,找到递增的位置是关键。因为在这里才可以使其增长得更大。于是找到了4,显而易见4过了是5而不是8或者7更不是1。因此就需要找出比4大但在这些大数里面最小的值,并将其两者调换。那么整个排列就成了:6 5 5 8 7 4 1然而最后一步将后面的8 7 4 1做一个递增。
代码如下:Your runtime beats 45.41% of java submissions.
public class Solution { public void nextPermutation(int[] nums) { if(nums == null) return;if(nums.length <= 1) return;int j = nums.length - 1;int smallest = nums.length - 1;while(j > 0){if(nums[j] > nums [j - 1]){j--; break;} j--;}if(j == 0 && nums[j] >= nums[j+1]){Arrays.sort(nums);return;}smallest = j + 1;for(int i = j ; i < nums.length; i++){if(nums[i] < nums[smallest] && nums[i] > nums[j]) smallest = i;}int temp = nums[smallest];nums[smallest] = nums[j];nums[j] = temp;for(int i = j + 1; i < nums.length; i ++){smallest = i;for(j = i; j < nums.length; j ++){if(nums[j] < nums[smallest]) smallest = j;}temp = nums[smallest];nums[smallest] = nums[i];nums[i] = temp;}return; }}
- [LeetCode]31.Next Permutation
- LeetCode --- 31. Next Permutation
- [Leetcode] 31. Next Permutation
- LeetCode 31.Next Permutation
- [leetcode] 31.Next Permutation
- [leetcode] 31. Next Permutation
- *LeetCode 31. Next Permutation
- Leetcode 31. Next Permutation
- leetcode 31. Next Permutation
- 31. Next Permutation LeetCode
- leetcode 31. Next Permutation
- leetcode 31. Next Permutation
- [LeetCode]31. Next Permutation
- [LeetCode]31. Next Permutation
- LeetCode 31. Next Permutation
- 【leetcode】31. Next Permutation
- LeetCode *** 31. Next Permutation
- leetcode 31. Next Permutation
- 在一个service中启动Activity
- LevelDB学习之路--README.MD
- sha1加密java代码
- CS231n-机器学习中matplotlib绘图基础.md
- iOS App Extension入门
- Leetcode-31. Next Permutation
- Servlet 生命周期、工作原理
- Tomcat配置Https协议
- cSS文件中第一行@charset "utf-8";的作用
- 存储结构与磁盘划分
- 单片机—花样灯—代码
- 颜色平衡和偏色调节
- Android:ViewPager适配器PagerAdapter的使用
- linux菜鸟入门之进程