Contains Duplicate

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:

Input: [1,2,3,1]
Output: true

Approach:

C++

#include <bits/stdc++.h>
using namespace std;

bool containsDuplicate(vector<int&nums)
{

    set<intst;
    for (int i = 0i < nums.size(); i++)
    {
        if (st.find(nums[i]!= st.end())
            return true;
        st.insert(nums[i]);
    }
    return false;
}

int main()
{
    vector<intnums = {1231};

    if (containsDuplicate(nums))
    {
        cout << "true";
    }
    else
    {
        cout << "false";
    }

    return 0;
}


No comments:

Post a Comment