一、题目描述

给定一个整数数组,判断是否存在重复元素。

如果存在一值在数组中出现至少两次,函数返回 true 。如果数组中每个元素都不相同,则返回 false 。


示例 1:
输入: [1,2,3,1]
输出: true

示例 2:
输入: [1,2,3,4]
输出: false

示例 3:
输入: [1,1,1,3,3,4,3,2,4,2]
输出: true

二、解题思路

对于数组中每个元素,我们将它插入到哈希表中。如果插入一个元素时发现该元素已经存在于哈希表中,则说明存在重复的元素。

三、代码

1、Python

class Solution(object):
    def containsDuplicate(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        dict={};
        for num in nums:
            cnt=dict.get(num,0)+1;
            if cnt>=2:
                return True;
            dict[num]=cnt;
        return False;

2、C++

class Solution {
public:
    bool containsDuplicate(vector<int>& nums) {
        unordered_set<int> s;
        for (int x: nums) {
            if (s.find(x) != s.end()) {
                return true;
            }
            s.insert(x);
        }
        return false;
    }
};

四、复杂度分析

时间复杂度:O(N),其中 N 为数组的长度。

空间复杂度:O(N),其中 N 为数组的长度。

欢迎关注微信公众号【算法攻城师】

Leetcode No.217 存在重复元素_函数返回