Wednesday, February 3, 2016

LeetCode Q31: 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


reverse() does not actually "sort" the array, it just reverse the order from start() to end() by swapping the pair one by one. So it is done in O(n). This code is a bit longer than optimal one on Leetcode, but since it is finished by myself without any refer to any source, I still keep it here for my own reference.

No comments:

Post a Comment