Contains Duplicate

Monisha Mathew
1 min readMay 8, 2019

--

Question: Given an array of integers, find if the array contains any duplicates.

Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.

Example 1:

Input: [1,2,3,1]
Output: true

You may view the full question here.

Approach 1: Let’s begin with the most straight forward approach —

//Approach 1:
//Runtime: 8ms
//Memory usage: 43.6MB
class Solution {
public boolean containsDuplicate(int[] nums) {
HashMap<Integer, Integer> map = new HashMap();
for(int n : nums){
if(map.containsKey(n)){
return true;
}
map.put(n, 0);
}
return false;
}
}

Find more posts here.

Cheers & Chao!

--

--