1. Contains Duplicate
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.
Code
class Solution {
public boolean containsDuplicate(int[] nums) {
HashMap<Integer, Integer> duplicateHashmap = new HashMap<Integer, Integer>();
for (int index = 0; index < nums.length; index++) {
if (duplicateHashmap.containsKey(nums[index])) {
return true;
} else {
duplicateHashmap.put(nums[index], 1);
}
}
return false;
}
}
The overall function of this code is to efficiently determine whether any number appears more than once in the given array. Please find the explanation below:
A
HashMap
namedduplicateHashmap
is created. This map will store the integers from thenums
array as keys. Each key in theHashMap
represents a unique number from the array.A
for
loop iterates through each element in thenums
array. Inside the loop, the code checks if the current number (nums[index]) is already a key in duplicateHashmap:If it is, this means the number is a duplicate, so the method immediately returns true.
If it isn't, the number is added to the duplicateHashmap with a value of
1
.
When adding a number to the
HashMap
, the code sets the value to1
withduplicateHashmap.put(nums[index], 1);
. This value doesn’t serve any specific purpose in this context because:We’re only interested in whether the key exists (indicating the number has already been seen).
The value (
1
in this case) does not provide any additional information or functionality.
If the loop completes without finding any duplicates, the method returns
false
, indicating that all elements in the array are unique.
Last updated