如果数组具有重复项,则输出应为true,否则,如果所有数组元素都是唯一的,则返回false。
例:
Input: [1, 2, 3, 1] Output: True Input:[1, 2, 3, 4] Output: False
方法1:通过使用set。
众所周知,set仅包含唯一元素。因此,我们将数组的所有元素插入到集合中,并检查原始长度和集合的长度是否相同。如果相同,则所有元素都是唯一的,否则我们有重复的元素。
方法2:通过排序。
我们对给定的数组进行排序,然后检查present元素和next元素。如果它们相同,则返回true,否则返回false。继续直到数组的结尾。
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; }
输出:
The array has duplicate elements.[method_1] The array has duplicate elements.[method_2]