Leetcode - Daily Temperatures
Leetcode - Find Elements in a Contaminated Binary Tree

Leetcode - Next Permutation

violet posted @ May 20, 2020 06:43:49 AM in 算法 with tags Algorithm Golang array , 188 阅读

https://leetcode.com/problems/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

 

func nextPermutation(nums []int)  {
    if len(nums) < 2 {
        return
    }
    i := len(nums)-2
    for i >= 0 {
        if nums[i] < nums[i+1] {
            break
        }
        i--
    }
    if i == -1 {
        reverse(nums)
        return
    }
    j := len(nums)-1
    for j > i {
        if nums[i] < nums[j] {
            break
        }
        j--
    }
    nums[i], nums[j] = nums[j], nums[i]
    reverse(nums[i+1:])
}

func reverse(nums []int) {
    size := len(nums)
    for i := 0; i < size/2; i++ {
        nums[i], nums[size-1-i] = nums[size-1-i], nums[i]
    }
}

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter