If the array has duplicates output should be true, else return false if all the array elements are unique.
Example:
Input: [1, 2, 3, 1] Output: True Input:[1, 2, 3, 4] Output: False
Method 1: By using set.
As we know that, set contains only unique elements. Hence we insert all the elements of the array in to the set and check if the original length and the length of the set is same. If same then all the elements are unique else we have a duplicate elements.
Method 2: By sorting.
We sort the given array, then check if the present element and the next element. If they are same return true else false. Continue till end of the array.
Solution in C++
#include<iostream> #include<string> #include<set> #include<vector> using namespace std; bool check_duplicate_method_1(vector<int>& array) { return set<int>(array.begin(), array.end()).size() < array.size(); } bool check_duplicate_method_2(vector<int>& array) { sort(array.begin(), array.end()); for (int i=0; i<int(array.size())-1; i++) { if (array[i]==array[i+1]) return true; } return false; } int main() { //test case 1 vector<int> array = {1, 2, 3, 1}; //test case 2 //vector<int> array = {1, 2, 3}; if(check_duplicate_method_1(array)) cout<<"The array has duplicate elements.[method_1]"<<endl; else cout<<"The array does not has duplicate elements.[method_1]"<<endl; if(check_duplicate_method_2(array)) cout<<"The array has duplicate elements.[method_2]"<<endl; else cout<<"The array does not has duplicate elements.[method_2]"<<endl; return 0; }
Output:
The array has duplicate elements.[method_1] The array has duplicate elements.[method_2]