Skip to content

Latest commit

 

History

History
69 lines (52 loc) · 2.22 KB

217.Contains_Duplicate_(Easy).md

File metadata and controls

69 lines (52 loc) · 2.22 KB

217. Contains Duplicate (Easy)

Link: https://leetcode.com/problems/contains-duplicate/

Similar question on neetcode: https://neetcode.io/problems/duplicate-integer/


Question:

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.


Example 1:

Input: nums = [1,2,3,1]

Output: true

Example 2:

Input: nums = [1,2,3,4]

Output: false

Example 3:

Input: nums = [1,1,1,3,3,4,3,2,4,2]

Output: true


KeyPoints:

This question is defintely faster to use set() to check for duplicate, and use the len to compare.


My Solution:

class Solution(object):
    def containsDuplicate(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        return (len(nums) != len(set(nums)))

Slower Solution:

This method will timeout for large list

class Solution(object):
    def containsDuplicate(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        n = 0
        for i in nums:
            if i in nums[n+1:]:
                return True
            n += 1
        return False

CC BY-NC-SABY: credit must be given to the creatorNC: Only noncommercial uses of the work are permittedSA: Adaptations must be shared under the same terms