More elegant way to check for duplicates in C++ array?

后端 未结 12 1437
梦如初夏
梦如初夏 2020-12-01 09:36

I wrote this code in C++ as part of a uni task where I need to ensure that there are no duplicates within an array:

// Check for duplicate numbers in user in         


        
12条回答
  •  忘掉有多难
    2020-12-01 10:07

    It is in extension to the answer by @Puppy, which is the current best answer.

    PS : I tried to insert this post as comment in the current best answer by @Puppy but couldn't so as I don't have 50 points yet. Also a bit of experimental data is shared here for further help.

    Both std::set and std::map are implemented in STL using Balanced Binary Search tree only. So both will lead to a complexity of O(nlogn) only in this case. While the better performance can be achieved if a hash table is used. std::unordered_map offers hash table based implementation for faster search. I experimented with all three implementations and found the results using std::unordered_map to be better than std::set and std::map. Results and code are shared below. Images are the snapshot of performance measured by LeetCode on the solutions.

    bool hasDuplicate(vector& nums) {
        size_t count = nums.size();
        if (!count)
            return false;
        std::unordered_map tbl;
        //std::set tbl;
        for (size_t i = 0; i < count; i++) {
            if (tbl.find(nums[i]) != tbl.end())
                return true;
            tbl[nums[i]] = 1;
            //tbl.insert(nums[i]);
        }
        return false;
    }
    

    unordered_map Performance (Run time was 52 ms here)

    Set/Map Performance

提交回复
热议问题