题目地址:
https://www.lintcode.com/problem/contains-duplicate/description
给定一个数组,判断其中是否有重复。用哈希表去重后看一下size和原数组长度是否相等即可,若不等则返回true。代码如下:
import java.util.HashSet;
import java.util.Set;
public class Solution {
/**
* @param nums: the given array
* @return: if any value appears at least twice in the array
*/
public boolean containsDuplicate(int[] nums) {
// Write your code here
if (nums == null || nums.length == 0) {
return true;
}
Set<Integer> set = new HashSet<>();
for (int num : nums) {
set.add(num);
}
return nums.length != set.size();
}
}
时空复杂度 O ( n ) O(n) O(n)。