题目链接: 存在重复的元素
有关题目
给定一个整数数组,判断是否存在重复元素。
如果存在一值在数组中出现至少两次,函数返回 true 。
如果数组中每个元素都不相同,则返回 false 。
示例 1:
输入: [1,2,3,1]
输出: true
示例 2:
输入: [1,2,3,4]
输出: false
示例 3:
输入: [1,1,1,3,3,4,3,2,4,2]
输出: true
题解
法一:排序
int cmp_int(const void* e1, const void* e2)
{
return *(int*)e1-*(int*)e2;
}
bool containsDuplicate(int* nums, int numsSize){
qsort(nums,numsSize,sizeof(int),cmp_int);
for(int i = 1; i < numsSize; i++)
{
if(nums[i] == nums[i - 1])
return true;
}
return false;
}
C++直接如下排序
sort(nums.begin(), nums.end())

法二:哈希表
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
unordered_set<int> s;
for (int x : nums)
{
if (s.find(x) != s.end())//s.end访问的是最后一个元素后面一个元素的地址
return true;
s.insert(x);
}
return false;
}
};


C版本哈希表
struct hashtable
{
int key;
UT_hash_handle hh;
};
bool containsDuplicate(int* nums, int numsSize){
struct hashtable* set = NULL;
for (int i = 0; i < numsSize; i++)
{
struct hashtable* tmp;
HASH_FIND_INT(set,nums + i,tmp);
if (tmp == NULL)
{
tmp = (struct hashtable*)malloc(sizeof(struct hashtable));
tmp->key = nums[i];
HASH_ADD_INT(set,key,tmp);
}
else
return true;
}
return false;
}


//(这个Hash超过时间限制,我的天 !!!)
typedef struct
{
int key;
}HashTable;
int FindNums(HashTable* Hash,int flag, int target)
{
for(int i = 0; i < flag; i++)
{
if(Hash[i].key == target)
return i;
}
return -1;
}
void InsertNums(HashTable* Hash,int index,int value)
{
Hash[index].key = value;
}
bool containsDuplicate(int* nums, int numsSize){
HashTable Hash[numsSize];
for(int i = 0; i < numsSize; i++)
{
if(FindNums(Hash,i,nums[i]) == -1)
InsertNums(Hash,i,nums[i]);
else
return true;
}
return false;
}
本文介绍了如何使用C++的快速排序和哈希表(unordered_set)来判断整数数组是否存在重复元素。通过实例和代码展示,提供了两种实用的算法来验证给定数组的唯一性。

3499

被折叠的 条评论
为什么被折叠?



