Uncategorized

arrays – List contains duplicate Python solution


I think this is what you need:

class Solution(object):
    def containsDuplicate(self, nums):
        i = 0
        while i < len(nums):
            if nums[i] in [n for n in nums if nums.index(n) != i]: # If a number in nums equals to nums[i], but in a different index...
                return True # That means there's a duplicate
            i+=1
        return False # Only return False if the program iterated through all the numbers and haven't return True
a = Solution()

print(a.containsDuplicate([1,2,8,3]))
print(a.containsDuplicate([1,2,8,3,8]))

Output:

False
True



Source link

Leave a Reply

Your email address will not be published. Required fields are marked *