Why sorted solution is faster than using unordered_set?


  • 0
    R

    This solution is 40ms

       bool containsDuplicate(vector<int>& nums) {
        unordered_set<int> s;
    
        for (auto n : nums) {
            auto it = s.insert(n);
            if (!it.second) return true;
        }
        return false;
    }
    

    And this solution takes less time to run

        bool containsDuplicate(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        for (size_t i = 1; i < nums.size(); i++) {
            if (nums[i-1] == nums[i]) return true;
        }
        return false;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.