36ms C++ solution using hash


  • 0
    M
    class Solution {
    public:
        bool containsDuplicate(vector<int>& nums) {
            int count=1000;
            vector<int> hash[count];
            for(int i=0;i<nums.size();i++)
            {
                int index=(nums[i]>=0?nums[i]:-nums[i])%count;
                for(int j=0;j<hash[index].size();j++)
                {
                    if(nums[i]==hash[index][j])
                        return true;
                }
                hash[index].push_back(nums[i]);
            }
            return false;
        }
    };

  • 0
    Z

    I see your idea. You use a simply hash function to reduce the running time.

    I use unordered_set, and the idea is exactly same as yours. But I guess std::unordered_set use a more complex hash function then it needs 48ms to run.


Log in to reply
 

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