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