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.
题意:给定一个整数数组。判断是否存在重复元素。
分类:数组,Hash
解法1:遍历数组,使用HashMap记录遍历过的数字,一旦重复,返回假
public class Solution {
public boolean containsDuplicate(int[] nums) {
HashMap<Integer,Integer> map =new HashMap<Integer,Integer>();
for(int i = 0;i<nums.length;i++){
if(map.containsKey(nums[i])){
return true;
}else{
map.put(nums[i], 0);
}
}
return false;
}
}