Next Permutation correct answer, OJ says wrong, Python


  • 0
    Z

    this is my code:

    class Solution:
    # @param {integer[]} nums
    # @return {void} Do not return anything, modify nums in-place instead.
    def nextPermutation(self, nums):
        if len(nums)<2:
            nums = nums
        else:
            currNumId = len(nums)-2
            while nums[-1] <= nums[currNumId] and currNumId >= 0:
                currNumId-=1
            if currNumId <0:
                nums = nums[::-1]
            else:
                nums[-1],nums[currNumId] = nums[currNumId],nums[-1]
                nums[currNumId+1:] = sorted(nums[currNumId+1:])
    

    in test case [1,3,2], I tested and successfully print the answer which is [2,1,3], but after I submit my solution, OJ says:

    Input:
    [2,3,1]
    Output:
    [2,3,1]
    Expected:
    [3,1,2]

    need help


  • 0

    nums = nums[::-1] creates a new list and leaves the original one unmodified.


  • 0
    Z

    thanks for your help, do you know any method I can fix it? I tried nums.reverse()...


  • 0

    Yes, nums.reverse() does fix that problem. You just still have some other bug.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.