31. Next Permutation

复制代码
package LeetCode_31

/**
 * 31. Next Permutation
 * https://leetcode.com/problems/next-permutation/description/
 *
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,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1
 * */
class Solution {
    /*
    Time complexity:O(n^2), Space complexity:O(1)
    * Approach
    ==Find the first decreasing index moving from end to start
        E.g. [7, 2, 3, 1, 5, 4, 3, 2, 0] num 1 is the first decreasing index going from the end backwards
    ==Swap num 1 with the next large num to its right which is 2
        [7, 2, 3, 2, 5, 4, 3, 1, 0]
    ==Reverse/sort nums to the right
        [7, 2, 3, 2, 0, 1, 3, 4, 5]
    ==If there is no next permutation return a sorted array
    * */
    fun nextPermutation(nums: IntArray): Unit {
        for (i in nums.size - 2 downTo 0) {
            if (nums[i] < nums[i + 1]) {
                val large = nextLargeIndex(nums, i)
                swap(nums, i, large)
                reverse(i+1,nums)
                return
            }
        }
        nums.sort()
    }

    private fun swap(nums: IntArray, i: Int, j: Int) {
        val temp = nums[i]
        nums[i] = nums[j]
        nums[j] = temp
    }

    private fun nextLargeIndex(nums: IntArray, index: Int): Int {
        for (i in nums.size - 1 downTo index) {
            if (nums[i] > nums[index]) {
                return i
            }
        }
        return 0
    }

    private fun reverse(index: Int, nums: IntArray) {
        var i = index
        var j = nums.size - 1
        while (i <= j) {
            swap(nums, i, j)
            i++
            j--
        }
    }
}
复制代码

 

posted @   johnny_zhao  阅读(116)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2019-06-28 设计模式-享元模式
点击右上角即可分享
微信分享提示