vendredi 13 novembre 2020

Why unordered_map is not giving correct answer every time while finding is there any duplicate value present in array or not?

I have given an array and I need to find, is there any duplicate present in array value or not? (I have to take input from the user.)

This is my first code which is giving the wrong answer for some test cases:

#include<bits/stdc++.h>
using namespace std;

#define forn(i, n) for (int i = 0; i < (int)(n); ++i)
 
 
int main() {
    // your code goes here
    int t;
    cin>>t;
    while(t--)
    {
        int n;
        cin>>n;
        unordered_map<int,int> mp;
        int temp=1;
        forn(i,n) 
        {
            int x; cin>>x;
            if(mp.find(x)!=mp.end()) 
            {
                temp=-1; break;
            }     
            
            mp[x]++;
        }
        if(temp==-1) cout<<"YES"<<endl; //if duplicate present
        else cout<<"NO"<<endl;
        mp.clear();
        
            
    }
    return 0;
}

And this code is running perfectly on all the test cases:

#include<bits/stdc++.h>
using namespace std;

#define forn(i, n) for (int i = 0; i < (int)(n); ++i)


int main() {
    // your code goes here
    int t;
    cin>>t;
    while(t--)
    {
        int n;
        cin>>n;
        unordered_map<int,int> mp;
        int temp=1;
        forn(i,n) 
        {
            int x; 
            cin>>x;
               
            
            mp[x]++;
        }
        
        if(mp.size()<n) cout<<"YES"<<endl;
        else cout<<"NO"<<endl;
        mp.clear();
        
            
    }
    return 0;
}

what is the reason behind it?

Aucun commentaire:

Enregistrer un commentaire