题目:
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.
此题刚开始使用bit-map解法,如下:
public boolean containsDuplicate(int[] nums) {
if(nums==null){
return false;
}
int max = 0;
for(int i=0;i<nums.length;i++){
if(nums[i]>max){
max = nums[i];
}
}
byte[] b = new byte[max+1];
for(int i=0;i<nums.length;i++){
b[nums[i]]++;
if(b[nums[i]]>1){
return true;
}
}
return false;
}
但如果输入负数会报错,所以直接使用HashSet,如下:
public class Solution {
public boolean containsDuplicate(int[] nums) {
Set<Integer> numSet = new HashSet<Integer>();
for(int i=0;i<nums.length;i++){
if(numSet.contains(nums[i]))
return true;
else
numSet.add(nums[i]);
}
return false;
}
}