Leetcode 31 Next permutationoop
[6, 2, 1, 5, 4 3] -> [6, 2, 3, 1, 4, 5]spa
[0, 1, 2] -> [0, 2, 1]code
[2, 1, 0] -> [0, 1, 2]blog
1) Find the key k such that nums[k] > nums[k+1] before the longest decreasing suffix which is [5, 4, 3], which is 1 in the first example. If there is no such element, the permutation must be [n-1, n-2, ..., 0], for which the reverse [0, ..., n-2, n-1] is the next permutation. This involves an iteration to the list, the time complexity is O(n)element
2) Find the smallest elment in the longest decreasing suffix such that nums[p] > num[k], swap(nums, p, k), to minimise the change to the prefix. This could be done by looping a subList, or binary search, O(n) or O(log(n))rem
3) After swap, the decreasing suffix after k remains decreasing order, to get the smallest suffix, need to reverse the suffix. O(n)get
public class NextP { public int findSmallestBiggerNum(int left, List<Integer> nums) { for(int i = nums.size()-1; i > left; --i) { if(nums.get(i) > nums.get(left)) return i; } return -1; } public List<Integer> nextP(List<Integer> nums) { int size = nums.size(); int firstIndex = size - 2; while(firstIndex >= 0 && nums.get(firstIndex) >= nums.get(firstIndex+1)) { --firstIndex; } if(firstIndex != -1) { int index = findSmallestBiggerNum(firstIndex, nums); Collections.swap(nums, firstIndex, index); } Collections.reverse(nums.subList(firstIndex+1, size)); return nums; } public static void main(String[] args) { NextP p = new NextP(); System.out.println(p.nextP(Arrays.asList(2)).toString().equals("[2]")); System.out.println(p.nextP(Arrays.asList(2, 0, 1)).toString().equals("[2, 1, 0]")); System.out.println(p.nextP(Arrays.asList(2, 1, 0)).toString().equals("[0, 1, 2]")); System.out.println(p.nextP(Arrays.asList(1, 0, 3, 2)).toString().equals("[1, 2, 0, 3]")); System.out.println(p.nextP(Arrays.asList(1, 3, 2, 1)).toString().equals("[2, 1, 1, 3]")); } }
We use only a few local variables, hence the space complexity is O(1)it