您的位置:首页 > 大数据 > 人工智能

Leetcode217. Contains Duplicate

2016-03-03 16:55 465 查看
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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: