LeetCode 🏔️/Array

217. Contains Duplicate

KB0129 2023. 1. 28. 09:28

Description:

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

Basically, we will look into the array, and then find out if there are same numbers. If there is a duplication in array, then we return "True", or not then "False". 

 

Solution1(not Answer):

permutaion(순열) method

 

Time Complexity for this algorithms O(N^2). In contrast, space complexity is O(1). When you submit this method, you can see the time complexity exceed for some case! That's definitely doesn't work.

 

Solution2(not Answer):

Sorting algorithms

This solution doesn't work for some case, and get wrong answer.

 

Solution3:

Third solution with set() 집합함수

The third solution is using set() in python. We actually made a set, and put the nums in it if it doesn't exist in seen. If there is a num already in seen and find out there are one duplicated number in nums, then return True.

 

Space complexity: O(N)

Time complexity: O(N)

 

Addition: 

I used the list instead of set(), but it exceeded the time limit. I learned that it is much faster to find some value in set or dict in this case!