题目描述

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.

解法一

思路

这题很简单,维持一个Set记录未出现重复的数,遍历数组,对每个数字先检查Set中是否已经存在,如存在则表明出现重复,返回False;如不存在,则将此数字加入到Set中;如遍历完未中途返回,则表明数组无重复,返回True。

Python

class Solution:
    def containsDuplicate(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        contains = set()
        for num in nums:
            if num in contains:
                return True
            contains.add(num)
        return False

Java

public class Solution {
    public boolean containsDuplicate(int[] nums) {
        Set<Integer> set = new HashSet<>();
        for (int num : nums) {
            if (set.contains(num)) {
                return true;
            }
            set.add(num);
        }
        return false;
    }
}

C++

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