--- tags: 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. Example 1: Input: [1,2,3,1] Output: true Example 2: Input: [1,2,3,4] Output: false Example 3: Input: [1,1,1,3,3,4,3,2,4,2] Output: true --- 輸入範本如下 ```C# public class Solution { public bool ContainsDuplicate(int[] nums) { } } ``` 自我限制 1. 不准使用 LinQ 的 Aggregate ```C# public bool ContainsDuplicate(int[] nums) { return nums.Aggregate(new HashSet<int>(), (set, num) => { set.Add(num); return set; }).Count != nums.Length; } ``` 2. 不准使用 LinQ 的 Distinct ```C# public bool ContainsDuplicate(int[] nums) => nums.Distinct().Count() != nums.Length; ``` 4. 不准使用 LinQ 的 Any ```C# public bool ContainsDuplicate(int[] nums) { var dict = new HashSet<int>(); return nums.Any(n => !dict.Add(n)); } ``` 5. 不准使用 LinQ 的 GroupBy ```C# public bool ContainsDuplicate(int[] nums) => nums.GroupBy(n => n).Any(group => group.Count() > 1); ``` ### 直覺想法 用一個迴圈依序把數字都裝入一個 Dict 內 , 若是曾經加入過 , 代表數字重複了 , 回傳 true , 反之若跑完迴圈則回傳 false ```C# 104 ms 31.9 MB You are here! Your runtime beats 95.70 % of csharp submissions. public bool ContainsDuplicate(int[] nums) { var dict = new HashSet<int>(); foreach (var num in nums) { if (!dict.Add(num)) // Add 回傳是否新加入成功的結果 , 因此可以少使用一個 Contains 去判斷是否包含. { return true; } } return false; } ``` 討論區一個很有趣的想法 , 因為在 HashSet 內 , 有多個相同的數字會被視為一個 , 因此當我把所有的數字都加入 HashSet 後 , 若有相同的數字 , 則 HashSet 的成員數量必定比原來的數字數量少 ```C# 108 ms 32.7 MB You are here! Your runtime beats 87.37 % of csharp submissions. public bool ContainsDuplicate(int[] nums) { var dict = new HashSet<int>(); foreach (var num in nums) { dict.Add(num); } return dict.Count() != nums.Length; } ``` 同討論區有趣的解法. 很直覺= = 將一個陣列排序後 , 若有重複的數字 , 則這些數字必定相鄰. ```C# 116 ms 28.7 MB You are here! Your runtime beats 52.47 % of csharp submissions. public bool ContainsDuplicate(int[] nums) { Array.Sort(nums); for (var i = 0; i < nums.Length - 1; i++) { if (nums[i] == nums[i + 1]) { return true; } } return false; } ``` ### Thank you! You can find me on - [GitHub](https://github.com/s0920832252) - [Facebook](https://www.facebook.com/fourtune.chen) 若有謬誤 , 煩請告知 , 新手發帖請多包涵 # :100: :muscle: :tada: :sheep: