LeetCode Array Easy 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: trueExample 2:
Input: [1,2,3,4] Output: falseExample 3:
Input: [1,1,1,3,3,4,3,2,4,2] Output: true
问题描述:给定一个数组,判断数组中是否存在重复元素,如果存在返回true,如果不存在返回false
思路:使用HashSet保存数组中的每个元素,如果在保存时HashSet中已经存在该元素,则返回true。
public bool ContainsDuplicate(int[] nums) { var hashSet = new HashSet<int>(); for(int i = 0; i < nums.Length; i++){ if(hashSet.Add(nums[i])==false) return true; } return false; }