mercredi 25 mars 2020

Is HashSet in Java faster than unordered_set in C++? and why>

I used these codes to solve problem Distribute Candies in leetcode https://leetcode.com/problems/distribute-candies/

in C++

int distributeCandies(vector<int>& candies) {
    unordered_set<int> s;
    for(int i=0;i<candies.size();i++){
        s.insert(candies[i]);
    }
    return min(s.size(),candies.size()/2);
}

and in Java

public int distributeCandies(int[] candies) {
    HashSet < Integer > set = new HashSet < > ();
    for (int candy: candies) {
        set.add(candy);
    }
    return Math.min(set.size(), candies.length / 2);
}

the first code ran in 384 ms and second code in 34 ms but why?

Aucun commentaire:

Enregistrer un commentaire