Leetcode31 Next Permutation
2015-07-28 00:25
579 查看
Next Permutation
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
Solution
可以举例观察特点。345
354
435
453
534
543
345
如上所述,实际操作过程可以分为三步:
第一步,从后往前找,找到第一个降序,比如453,45这里是一个降序,降序处的数为4;
第二步,从后往前找找到第一个比4大的那个数,这里是5,交换4和5的位置;
第三步,将原先4位置后面的数进行翻转,比如这里是先得到543,然后再将43翻转得到最终的答案为534。
用代码表示如下:
public class Solution { public void nextPermutation(int[] nums) { int n = nums.length; int i = n-2, j = n-1, temp; for(;i>=0;i--) if(nums[i]<nums[i+1]) break;//从后往前找到第一个降序 if(i>=0){ temp = nums[i]; for(;j>=0;j--) if(nums[j]>temp) break;//从后往前找到第一个比降序处的数大的数 nums[i] = nums[j];//交换这两个数 nums[j] = temp; } for(i++,j=n-1;i<j;i++,j--){//翻转后面的所有数 temp = nums[j]; nums[j] = nums[i]; nums[i] = temp; } } }
当然,有些解法里面在第二步的时候用二分法去找比4大的那个数,这样运行速度稍微会好些,但是时间复杂度仍为O(N),并且代码也要更加复杂一些。感兴趣的可以自己尝试去实现一下。
4000
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解
- LeetCode [Day 5] Longest Palindromic Substring 题解
- LeetCode [Day 6] ZigZag Conversion 题解