Leetcode1346. 检查整数及其两倍数是否存在

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;
}

结果:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

UestcXiye

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值