Contains Duplicate 解答

时间:2024-07-18 13:37:38

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.

Solution 1 HashMap

Time complexity O(n), space cost O(n)

 public class Solution {
public boolean containsDuplicate(int[] nums) {
Map<Integer, Integer> counts = new HashMap<Integer, Integer>();
int length = nums.length;
if (length <= 1)
return false;
for (int i = 0; i < length; i++) {
if (counts.containsKey(nums[i]))
return true;
else
counts.put(nums[i], 1);
}
return false;
}
}

Solution 2 Set

Time complexity O(n), space cost O(n)

 public class Solution {
public boolean containsDuplicate(int[] nums) {
int length = nums.length;
if (length <= 1)
return false;
Set<Integer> set = new HashSet<Integer>();
for (int i : nums) {
if (!set.add(i))
return true;
}
return false;
}
}