题目:
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.
代码:
public class Solution {
public boolean containsDuplicate(int[] nums) {
boolean flag = false;
HashMap hm = new HashMap();
for(int i=0; i<nums.length; i++){
if(!hm.containsKey(nums[i])){
hm.put(nums[i],1);
}
else{
flag = true;
break;
}
}
return flag;
}
}
注意:
1、数组a求长度用a.length,而不是a.length()
2、本题用HashMap来做会很简单。只要将数组中的数当键值key,出现的次数当value,当发现数组中包含某个键值key时,说明有重复,则直接跳出循环。