leetcode 31
来源:互联网 发布:贪吃蛇大作战 算法 编辑:程序博客网 时间:2024/06/01 15:00
【题目】
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
【思路】
实现了C++中stl::next_permutation的思路,即
在当前序列中,从尾端往前寻找两个相邻元素,前一个记为*i,后一个记为*ii,并且满足*i < *ii。然后再从尾端寻找另一个元素*j,如果满足*i < *j,即将第i个元素与第j个元素对调,并将第ii个元素之后(包括ii)的所有元素颠倒排序,即求出下一个序列
【Java代码】
public void nextPermutation(int[] nums){if(nums.length >1){int i = nums.length-2,ii = nums.length-1,j = ii;boolean flag = false;while(i >= 0)if(nums[i] < nums[ii]){flag = true;break;}else{i--; ii--;}if(flag){while(j >= 0)if(nums[j] > nums[i])break;elsej--; int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp;}else{ii = 0;}for(int start = ii,end = nums.length-1 ; start < end; start++,end--){int temp = nums[start];nums[start] = nums[end];nums[end] = temp;}}}
阅读全文
0 0
- Leetcode 31
- leetcode 31
- LeetCode 31
- LeetCode 31: Next Permutation
- [LeetCode] Subsets [31]
- [leetcode 31] Next Permutation
- LeetCode(31) Next Permutation
- [leetcode]31 Symmetric Tree
- 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
- LeetCode 31 - Next Permutation
- hprofile教程
- 模拟实现memcpy和memmove——题集(二十二)
- Spark 基础及RDD基本操作
- java中的sleep()和wait()的区别
- Java反射机制
- leetcode 31
- okhttp网络框架的封装实用
- gulp详细入门教程
- 一步快速将Smartform output转成生成PDF文件
- Java面向对象基础
- excel文件读写(python版)
- codeforces 837A Text Volume
- SQLServer资源调控器--自由分配您的资源
- Chrome的使用方法