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.
Subscribe to see which companies asked this question
题目:给定一个整数数组,判断数组中是否有重复数字
思路1:
使用hash表,先构建,然后遍历,发现value大于1则判断有重复
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
int tmp=0;
unordered_map<int,int> hash;
for(auto a:nums)
hash[a]++;
for(auto a:hash)
if(a.second>=2)
{
tmp=1;
break;
}
if(tmp==1)
return true;
else
return false;
}
};
思路2:
使用异或位运算,如果没有重复,则结果不为0,反之,当异或结果第一次变为0时,即可推出程序,判断数组中有重复数字!
思路3:对数组排序,遍历相邻数字是否相等
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
std::sort(nums.begin(), nums.end());
for (int i = 1; i < nums.size(); i++) {
if (nums[i-1] == nums[i]) return true;
}
return false;
}
};