多种方法实现查找

查找

https://www.nowcoder.com/practice/d93db01c2ee44e8a9237d63842aca8aa?tpId=40&&tqId=21531&rp=1&ru=/ta/kaoyan&qru=/ta/kaoyan/question-ranking

线性查找

#include <iostream>
#include <cstdio>
#include <algorithm>

using namespace std;
const int MAX=100;
int arr[MAX];

bool LinSearch(int n,int target){
    for(int i=0;i<n;i++)
        if(arr[i]==target)
            return true;
    return false;
}

int main(){
    int n;
    scanf("%d",&n);
    for(int i=0;i<n;i++)           //由n控制输入个数
        scanf("%d",&arr[i]);
    int m;
    scanf("%d",&m);
    while(m--){                    ////由m控制比较个数
        int target;
        scanf("%d",&target);
        if(LinSearch(n, target))
            printf("YES\n");
        else
            printf("NO\n");
    }
    return 0;
}

二分查找

#include <iostream>
#include <cstdio>
#include <algorithm>

using namespace std;
const int MAX=100;
int arr[MAX];

bool BinarySearch(int n, int target){
    int left=0;
    int right=n-1;
    while(left<=right){
        int middle=left+(right-left)/2;
        if(arr[middle]<target)
            left=middle+1;
        else if(arr[middle]>target)
            right=middle-1;
        else
            return true;
    }
    return false;
}

int main(){
    int n;
    scanf("%d",&n);
    for(int i=0;i<n;i++)           //由n控制输入个数
        scanf("%d",&arr[i]);
    sort(arr, arr+n);                //二分查找的前提是数组arr要求有序
    int m;
    scanf("%d",&m);
    while(m--){                    ////由m控制比较个数
        int target;
        scanf("%d",&target);
        if(BinarySearch(n, target))
            printf("YES\n");
        else
            printf("NO\n");
    }
    return 0;
}

散列查找

#include <iostream>
#include <cstdio>
#include <algorithm>

using namespace std;
const int MAX=100;
int arr[MAX];
int HashTable[MAX];


int main(){
    int n;
    scanf("%d",&n);
    for(int i=0;i<n;i++){
        scanf("%d",&arr[i]);
        HashTable[arr[i]]=true;        //出现这个值,就把对应HashTable的值赋值为true
    }           //由n控制输入个数
    int m;
    scanf("%d",&m);
    while(m--){                    ////由m控制比较个数
        int target;
        scanf("%d",&target);
        if(HashTable[target])        //通过target对应HashTable是否有值存在
            printf("YES\n");
        else
            printf("NO\n");
    }
    return 0;
}
全部评论

相关推荐

大飞的诡术妖姬:之前看b站多明海有个说法,日本就业竞争非常低的原因不光是毕业学生少,还有很多人干两年不喜欢职场氛围就辞职躺平,位置也空了很多,论吃苦耐劳还得看咱们
点赞 评论 收藏
分享
05-19 15:21
已编辑
华南农业大学 Java
白火同学:你才沟通了200,说实话,北上广深杭这里面你连一座城市的互联网公司都没投满呢,更别说还有各种准一线二线城市了。等你沟通突破了三位数,还没结果再考虑转行的事吧。
点赞 评论 收藏
分享
06-10 23:36
已编辑
首都经济贸易大学 C++
点赞 评论 收藏
分享
06-27 15:15
长安大学 Java
哈哈哈,你是老六:这种就是培训机构骗钱的
点赞 评论 收藏
分享
评论
2
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务