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 and use only constant 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,31,3,2
3,2,11,2,3
1,1,51,5,1

Solution

(1) Java

class Solution {
    public void nextPermutation(int[] nums) {
        if (nums == null || nums.length == 0) {
            return;
        }
        for (int i = nums.length-2; i >= 0; i--) {
            if (nums[i] < nums[i+1]) {
                for (int j = nums.length-1; j > i; j--) {
                    if (nums[j] > nums[i]) {
                        int tmp = nums[i];
                        nums[i] = nums[j];
                        nums[j] = tmp;
                        for (int k = j-1; k > i; k--) {
                            if (nums[k] < nums[k+1]) {
                                int tmp2 = nums[k+1];
                                nums[k+1] = nums[k];
                                nums[k] = tmp2;
                            }
                        }
                        swap(nums, i+1);
                        return;
                    }
                }
            }
        }
        swap(nums, 0);
    }

    private void swap(int[] nums, int start) {
        int i = start;
        int j = nums.length-1;
        while (i < j) {
            int tmp = nums[i];
            nums[i] = nums[j];
            nums[j] = tmp;
            i++;
            j--;
        }
    }
}

(2) Python

class Solution:
    def nextPermutation(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        def reverse(start):
            end = len(nums)-1
            while start < end:
                x = nums[start]
                nums[start] = nums[end]
                nums[end] = x
                start += 1
                end -= 1

        if not nums:
            return
        i = 0
        reverseWhole = True
        for i in range(len(nums)-2, -1, -1):
            if nums[i] < nums[i+1]:
                for j in range(len(nums)-1, -1, -1):
                    if nums[j] > nums[i]:
                        tmp = nums[i]
                        nums[i] = nums[j]
                        nums[j] = tmp
                        break
                reverseWhole = False
                break 
        if reverseWhole:
            reverse(0)
        else:
            reverse(i+1)

(3) Scala



results matching ""

    No results matching ""