Title:Contains Duplicate 217
Difficulty:Easy
原题leetcode地址:https://leetcode.com/problems/contains-duplicate/
1. 采用HashMap的key的唯一性,时间&空间复杂度如下:
时间复杂度:O(n),一次for循环,遍历整个数组的长度。
空间复杂度:O(n),申请整个一个HashMap,最长需要存放n个。
/**
* 采用HashMap中key的唯一性
* @param nums
* @return
*/
public static boolean containsDuplicate(int[] nums) {
if (nums == null || nums.length <= 0) {
return false;
}
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(nums[i])) {
return true;
}
else {
map.put(nums[i], 1);
}
}
return false;
}
2. 采用Set集合的唯一性,时间&空间复杂度如下:
时间复杂度:O(n),一次for循环,遍历整个数组的长度。
空间复杂度:O(n),申请整个一个HashSet,最长需要存放n个。
/**
* 采用Set集合的唯一性
* @param nums
* @return
*/
public static boolean containsDuplicate1(int[] nums) {
if (nums == null || nums.length <= 0) {
return false;
}
Set<Integer> set = new HashSet<>();
for (int i = 0; i < nums.length; i++) {
if (set.contains(nums[i])) {
return true;
}
else {
set.add(nums[i]);
}
}
return false;
}
同样的时间复杂度,但是在执行过程中,set比map快很多: