【LeetCode】217. Contains Duplicate(sort,hash,map)

1412 ワード

Question
Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.
Code
mapを使って、C++11の新しい特性autoを使って、とても知能的で便利ですハハ~
    bool containsDuplicate(vector<int>& nums) {
        map<int, int> cnt;
        for (auto num : nums)
            cnt[num]++;
        for (auto num : cnt)
            if (num.second > 1) return true;
        return false;
    }

でも時間的にちょっと悪いので96 msかかりました
hashを使用すると48 msに減少します
mapは赤黒ツリーを用いて実現され、検索速度はlog(n)レベルである.
hash検索速度は基本的にデータ量サイズとは無関係です.
しかし、mapよりもhashが速いわけではありません.hashにはhash関数が必要で、構造が遅いからです.
また,本題では配列を並べ替え,隣接する要素が同じか否かを判断すればよい.