The Question is:
Given an integer array
true if any value appears at least twice in the array, and return
false if every element is distinct.
Let us say that we have a list of random numbers and not necessarily in an ordered manner. Your goal is to find out if there is any duplicates of elements or none in the list of the numbers provided. In case there is duplicate, you should return True and if there is no duplicate, then return False. For instance the array [1,1,1,3,3,4,3,2,4,2] and [1,2,3,1] will output True while the array [1,2,3,4] will output False.
To approach this problem, one can easily use set data method. This is because set does not allow duplicates, while array does.
According to Python Collections (Arrays):
Normally, there are four collection data types in the Python programming language:
- List – A collection of data which is ordered, changeable, and allows duplicate members.
- Tuple – A collection of data which is ordered, unchangeable, but allows duplicate members.
- Set – A collection of data which is unordered, unchangeable, unindexed, and has NO duplicate members.
- Dictionary – A collection of data which is ordered, changeable, but NO duplicate members.
Therefore, if we get to convert the arrays provided into sets, then those with duplicate elements will be reduced. Then we can use the length function to check if any of the lengths of the sets have changed. Those with reduced length means they had duplicate elements in them, thus, returns True. While those retaining the same length means they have no duplicate elements, thus returns False.
We can solve the problem by matching the lengths of the sets as follow;
class Solution(object): def containsDuplicate(self, nums): return not len(nums) == len(set(nums)) ob1 = Solution() print(ob1.containsDuplicate([1,1,1,3,3,4,3,2,4,2])) print(ob1.containsDuplicate([1,2,3,4])) print(ob1.containsDuplicate([1,2,3,1]))
True False True
If you have any question or comments, do not hesitate to ask us.
Quote: The moon looks upon many night flowers; the night flowers see but one moon. – Jean Ingelow