Every day a leetcode
题目来源:1346. 检查整数及其两倍数是否存在
解法1:暴力
两个for循环。
代码:
bool checkIfExist(int* arr, int arrSize){
int n=arrSize;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(i!=j && arr[i] == 2*arr[j]) return true;
}
}
return false;
}
结果:
解法2:hash
用hash统计arr数组的每一个值,注意正数和负数要分开处理。
代码:
#define MAX_HASH_LENGTH 2001
int abs(int x)
{
return x>0?x:-x;
}
bool check(int* hash,int x)
{
if(hash[2*x]>0) return true;
if(x%2 == 0 && hash[x/2]>0) return true;
hash[x]++;
return false;
}
bool checkIfExist(int* arr, int arrSize){
int n=arrSize;
int hash_p[MAX_HASH_LENGTH];
int hash_n[MAX_HASH_LENGTH];
memset(hash_p,0,sizeof(hash_p));
memset(hash_n,0,sizeof(hash_n));
for(int i=0;i<n;i++)
{
int x=arr[i];
if(x>0)
{
if(check(hash_p,x)) return true;
}
else
{
if(check(hash_n,abs(x))) return true;
}
}
return false;
}
结果:
优化
我们发现,hash[i]只要大于0,是 1 是 2 完全没区别,只是有0和非0的区别。
于是,我们把hash表改成bool型。
代码:
#define MAX_HASH_LENGTH 2001
int abs(int x)
{
return x>0?x:-x;
}
bool check(bool* hash,int x)
{
if(hash[2*x]) return true;
if(x%2 == 0 && hash[x/2]) return true;
hash[x]=true;
return false;
}
bool checkIfExist(int* arr, int arrSize){
int n=arrSize;
bool hash_p[MAX_HASH_LENGTH];
bool hash_n[MAX_HASH_LENGTH];
memset(hash_p,false,sizeof(hash_p));
memset(hash_n,false,sizeof(hash_n));
for(int i=0;i<n;i++)
{
int x=arr[i];
if(x>0)
{
if(check(hash_p,x)) return true;
}
else
{
if(check(hash_n,abs(x))) return true;
}
}
return false;
}
结果: