[Python] Why is my C++ method slower than Python function [closed]

Discussão em 'Python' iniciado por Stack, Abril 7, 2025.

  1. Stack

    Stack Membro Participativo

    So, I tried to do some LeetCode the other day, and for some reason, this Python code:

    def containsDuplicate(self, nums: List[int]) -> bool:
    hashset = set()
    for num in nums:
    if num in hashset:
    return True
    hashset.add(num)
    return False


    runs at 6ms screenshot here

    but this roughly same C++ code:

    bool containsDuplicate(vector<int>& nums) {
    std::unordered_set<int> hashset;
    for(int num : nums){
    if (hashset.count(num) > 0) return true;
    hashset.insert(num);
    }
    return false;
    }


    runs at 29ms screenshot here

    Both check if array has duplicates

    To be honest, I'm new to C++, so I might be wrong here, but I'm just curious what's wrong exactly

    Continue reading...

Compartilhe esta Página