[Python] LeetCode 'Contains Duplicate' solution doesn't work as expected [duplicate]

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

  1. Stack

    Stack Membro Participativo

    I just tried a random LeetCode problem: 217 - Contains Duplicate. My code works on the 3 testcases when I run, but failed on testcase 68.

    The exact question states:


    Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.
    ​

    Code submitted was as below:

    class Solution:
    def containsDuplicate(self, nums: List\[int\]) -\> bool:
    for n in nums:
    nums.remove(n)
    if n in nums:
    return True
    return False


    I'm sure I can find another solution or look one up online but I wonder if anyone knows what is wrong with this code so that it fails after 67 testcases. In my mind this code should produce the intended results specified in the question. I'll appreciate any insight into what went wrong with this seemingly simple algorithm.

    Continue reading...

Compartilhe esta Página