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.
Input: nums = [1,2,3,1]
Output: trueInput: nums = [1,2,3,4]
Output: falseInput: nums = [4,4,4,2,3,4,5,6,6]
Output: true
My first solution (Not very good):
class Solution {
public boolean containsDuplicate(int[] nums) {
int length = nums.length;
for(int i=0; i<length; i++){
for(int j=i+1; j<length;j++)
{
if(nums[i]==nums[j])
{
return true;
}
}
}
return false;
}
}
Second solution- I tried using Java Hashmap which got accepted but I am not happy, why to use hashmap while I only need to store 1 data point
class Solution {
public boolean containsDuplicate(int[] nums) {
int length = nums.length;
HashMap<Integer, Integer> collection = new HashMap<>();
for(int i=0; i<length; i++){
if(collection.containsKey(nums[i])){
return true;
}else{
collection.put(nums[i],0);
}
}
return false;
}
}