LeetCode Array Easy 217. Contains Duplicate

Description

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

问题描述:给定一个数组,判断数组中是否存在重复元素,如果存在返回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;
    }

 

 

posted @ 2018-09-04 10:53  C_supreme  阅读(146)  评论(0编辑  收藏  举报