?
要求:
给定一个整型数组,判断它是否包含重复元素。当任一元素函数应当返回true,当所有元素各不相同时返回false。
?
难度:简单
?
分析:
与#1 Two Sum类似,可以两次循环遍历,依次判断每一个元素是否在其后出现;或者使用一个HashSet作为辅助结构,遍历数组,若某元素不在HashSet中则将其加入Set,若在Set中已存在则直接返回true。
?
解决方案:
Java - 460ms
public boolean containsDuplicate(int[] nums) {
? ? ? ? Set<Integer> uniqueSet = new HashSet<Integer>();
?
? ? ? ? for(int i=0; i<nums.length; i++){
? ? ? ? ? ? if(uniqueSet.contains(nums[i])){
? ? ? ? ? ? ? ? return true;
? ? ? ? ? ? }else {
? ? ? ? ? ? ? ? uniqueSet.add(nums[i]);
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? return false;
? ? }
LeetCode[Array] - #217 Contains Duplicate
原文:http://cwind.iteye.com/blog/2232058