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<Integer, Integer> hm=new HashMap<Integer, Integer>();
for(int i=0;i<nums.length;i++)
{
if(!hm.containsKey(nums[i]))
hm.put(nums[i], 1);
else
{
flag=true;
break;
}
}
return flag;
}
}
本文介绍了一种使用哈希表来检测数组中是否存在重复元素的方法。通过遍历数组并使用哈希表记录元素出现情况,可以高效地判断数组中是否含有重复项。
337

被折叠的 条评论
为什么被折叠?



