Leetcode Journey(1): 217. Contains Duplicate
I started my new year off with a simple leetcode easy problem.
The question is simple enough, just check if there are any duplicate values in the given integer array and return true if yes and false otherwise.
Solution:
At first glance, we could do this by comparing each array element with every other element in the array. That would take us longer. Instead, we can make use of the HashMap collection. This would considerably be faster. I just kept thinking what other way would be faster and happened to stumble on going this route.
HashMap does not allow duplicates keys. So, if you put all the array elements in it and then finally compare the size with the array. We will know if the array has any duplicates or not.
- If the array & HashMap sizes are same, then there are no duplicates.
- If the sizes are different, HashMap would be lesser, which indicates there were duplicates.
class Solution {
public boolean containsDuplicate(int[] nums) {
Map map = new HashMap<Integer,Integer>();
for(int i: nums){
map.put(i,0);
}
if(nums.length==map.size()){
return false;
}else{
return true;
}
}
}
Performance:
Although I am not too concerned about getting the best solution possible, I am still checking the performance of my solution to make sure my code it as fast and efficient as possible.
It only beats 39% people so this is an likely an average solution. I would be very happy if I get better than 80%. I am still happy that I solved my first problem this year.