[Python] Inline vs Function-based Swapping (First Missing Positive)

Discussão em 'Python' iniciado por Stack, Setembro 23, 2024.

  1. Stack

    Stack Membro Participativo

    I am trying to solve this leetcode problem: First Missing Positive. However, I am facing a problem while performing the swap.

    I referred to the solution here.

    So instead of having a helper function like this to perform the swap,

    class Solution:
    def firstMissingPositive(self, nums: List[int]) -> int:
    def swap_elements(index1, index2):
    nums[index1], nums[index2] = nums[index2], nums[index1]

    list_length = len(nums)

    for i in range(list_length):
    while 1 <= nums <= list_length and nums != nums[nums - 1]:
    swap_elements(i, nums - 1)

    for i in range(list_length):
    if i + 1 != nums:
    return i + 1

    return list_length + 1


    I tried to perform an inline swap like this

    class Solution:
    def firstMissingPositive(self, nums: List[int]) -> int:
    list_length = len(nums)

    for i in range(list_length):
    while 1 <= nums <= list_length and nums != nums[nums - 1]:
    nums, nums[nums - 1] = nums[nums - 1], nums

    for i in range(list_length):
    if i + 1 != nums:
    return i + 1

    return list_length + 1


    Both approaches use the same logic, but the second does not work for some inputs.

    Example: Given the input [3,4,-1,1], the first approach will change the nums like this

    [-1, 4, 3, 1] --> [-1, 1, 3, 4] --> [1, -1, 3, 4]

    but the second approach will cause an infinite while loop

    [-1, 4, 3, 1] --> [4, 1, 3, 1] --> [4, 4, 3, 1] --> [4, 1, 3, 1] --> [4, 4, 3, 1]...

    Continue reading...

Compartilhe esta Página