# C#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.

Input: [1,2,3,1]

Output: true

Input: [1,2,3,4]

Output: false

Input: [1,1,1,3,3,4,3,2,4,2]

Output: true

```public class Program {

public static void Main(string[] args) {
int[] nums = null;

nums = new int[] { 1, 2, 3, 4, 5, 6, 7, 7 };
var res = ContainsDuplicate(nums);
Console.WriteLine(res);

nums = new int[] { 1, 2, 3, 4, 5, 6, 7, 8 };
res = ContainsDuplicate2(nums);
Console.WriteLine(res);

nums = new int[] { 1, 2, 3, 3, 5, 6, 7, 8 };
res = ContainsDuplicate3(nums);
Console.WriteLine(res);

}

private static bool ContainsDuplicate(int[] nums) {
//暴力解法
for(int i = 0; i < nums.Length; i++) {
for(int j = i + 1; j < nums.Length; j++) {
if(nums[i] == nums[j]) return true;
}
}
return false;
}

private static bool ContainsDuplicate2(int[] nums) {
//先排序，再使用单循环比较相邻值
Array.Sort(nums);
for(int i = 0; i < nums.Length - 1; i++) {
if(nums[i] == nums[i + 1]) return true;
}
return false;
}

private static bool ContainsDuplicate3(int[] nums) {
//哈希法
var dic = new Dictionary<int, int>();
foreach(var num in nums) {
if(dic.ContainsKey(num)) return true;
dic[num] = 0;
}
return false;
}

}```

```True
False
True```

(2)