# LeetCode 217. Contains Duplicate

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.

HashSet？

first try:

import java.util.HashSet;

class Solution {
public boolean containsDuplicate(int[] nums) {
HashSet<Integer> hashSet = new HashSet<Integer>();

for(int i=0; i<nums.length; i++) {
if(hashSet.contains(nums[i]) ) {
return true;
} else {
}
}

return false;
}
}

result:

second:

import java.util.HashSet;

class Solution {
public boolean containsDuplicate(int[] nums) {
HashSet<Integer> hashSet = new HashSet<Integer>();

for(int i=0; i<nums.length; i++) {
int num = nums[i];
if(hashSet.contains(num) ) {
return true;
} else {
}
}

return false;
}
}

result:

the same.

third:

import java.util.HashSet;

class Solution {
public boolean containsDuplicate(int[] nums) {
HashSet<Integer> hashSet = new HashSet<Integer>();

int length = nums.length;
for(int i=0; i<length; i++) {
int num = nums[i];
if(hashSet.contains(num) ) {
return true;
} else {
}
}

return false;
}
}

result:

anylysis:

import java.util.HashSet;

public class Solution {
public boolean containsDuplicate(int[] nums) {
Set<Integer> set = new HashSet<Integer>();
for (int x: nums) {
if (set.contains(x)) {
return true;
} else {
}

}
return false;
}
}

result:

32.96%

import java.util.HashSet;

public class Solution {
public boolean containsDuplicate(int[] nums) {
Set<Integer> set = new HashSet<Integer>();
int length = nums.length;
for(int i=0; i<length; i++) {
if (set.contains(nums[i])) {
return true;
} else {
}

}
return false;
}
}

17.88%

for 和foreach循环速度在都是HashSet时没有变化；在是Set时有变化。

import java.util.HashSet;

public class Solution {
public boolean containsDuplicate(int[] nums) {
Set<Integer> set = new HashSet<Integer>();
for (int x: nums) {
if (set.contains(x)) {
return true;
} else {