题意:给你一个数组,问你其中有没有相同的元素。
思路:这个题有1W种解法,但是为了练习嘛,我就选了用哈希表来做这道题目。。。虽然麻烦。。但是达到了训练的目的。。。
class Solution{
private:
const static int MOD = 1000007;
struct HashMap{
int val;
HashMap *next;
HashMap() {}
HashMap(int val) : val(val) {next = NULL;}
};
HashMap **hashmap = new HashMap*[MOD];
bool Insert(int val){
int va = val > 0 ? val : -val;
int key = va % MOD;
HashMap *tmp = hashmap[key];
while(tmp){
if(tmp->val == val)
return true;
tmp = tmp->next;
}
tmp = new HashMap(val);
tmp->next = hashmap[key];
hashmap[key] = tmp;
return false;
}
public:
bool containsDuplicate(vector<int> &nums){
for(int i = 0; i < nums.size(); i++){
if(Insert(nums[i]))
return true;
}
return false;
}
};