Likou brush question record vol.6 - there are repeated elements

A very simple question, and the practice is relatively easy to understand.

Method 1: Sort

Because the same numbers must be in adjacent positions after sorting, the sorted array can be scanned. If two adjacent numbers are equal, there are duplicate elements.

class Solution {
public:
    bool containsDuplicate(vector<int>& nums) {
        sort(nums.begin(),nums.end());
        int n = nums.size();
        for(int i=0;i<n-1;i++)
        {
            if(nums[i] == nums[i+1])
                return true;
        }
        return false;
    }
};

 

 

Method 2: Hash Table

        

        For each element in the array, we insert it into the hash table. If when inserting an element, it is found that the element already exists in the hash table, then there is a duplicate element.

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

 

Guess you like

Origin blog.csdn.net/HimaRe1/article/details/131198279