首页 > 代码库 > 31. Next Permutation
31. 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
链接:https://leetcode.com/problems/next-permutation/#/description
4/14/2017
20ms, 65%
大致的思路:从后往前遍历,当碰到第一个变小的趋势时停止,记录index。如果不是因为下标溢出的停止时,我们再从后往前找第一个比index的值大的值,然后交换两个元素。再从index开始做sort。第二遍遍历时其实可以用binarysearch的revese版本,但是Java里int, Integer, array, ArrayList换的我头疼,直接就顺序查找了。
1 public class Solution { 2 public void nextPermutation(int[] nums) { 3 if (nums.length <= 1) return; 4 int i = nums.length - 2; 5 while(i >= 0) { 6 if (nums[i] < nums[i + 1]) break; 7 i--; 8 } 9 if (i >= 0) { 10 int j = nums.length - 1; 11 while (nums[j] <= nums[i] && j > i) { 12 j--; 13 } 14 int tmp = nums[i]; 15 nums[i] = nums[j]; 16 nums[j] = tmp; 17 } 18 Arrays.sort(nums, i + 1, nums.length); 19 return; 20 } 21 }
官方解答,与我的想法一样:https://leetcode.com/articles/next-permutation/
更多讨论:https://discuss.leetcode.com/category/39/next-permutation
31. Next Permutation