leetcode Question: Contains Duplicate

Contains Dulplicate

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.


This is an easy question and there are many ways to do it.
One way is to firstly sort the array, and check each two elements to see if they are equal.
Another way is to utilize the hash map (map in C++ STL), create the map at the same time check if there exists any duplicates.


class Solution {
    bool containsDuplicate(vector<int>& nums) {
        if (nums.size()==0){
            return false;
        map<int, bool> mp;
        for (int i=0;i<nums.size();i++){
            if (mp.find(nums[i])==mp.end()){
                mp[nums[i]] = true;
            } else{
                return true;
        return false;


class Solution(object):
    def containsDuplicate(self, nums):
        :type nums: List[int]
        :rtype: bool
        if len(nums) == 0:
            return False
        mp = {}
        for num in nums:
            if not mp.get(num):
                mp[num] = True
                return True
        return False

No comments:

Post a Comment