Fastest way to search for an element in unsorted array

后端 未结 10 1800
北恋
北恋 2020-12-14 08:13

I just bumped on to this question today and was trying for a solution that is better than O(N) but could not come up with one.

Searched through SO but couldn\'t find

10条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-14 08:52

    You can search an element with O(1) using this approach.

    Just create a MAP . When you insert a value just then for that key assign value to '1', and to search it again just check if that array is present or not .

    Below is the code:-

    #include
    
    using namespace std;
    
    int main(){
        int n;
        cin>>n;
        map map;
        for(int i=0;i>k;
            map[k]=1;
        }
        int num;
        cin>>num;
    
        if(map[num]){
            cout<<"FOUND"<

    Output :FOUND

提交回复
热议问题