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

来源:互联网 发布:网络信息安全的特点 编辑:程序博客网 时间:2024/06/03 16:09

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;    }

不过时间方面有点差,用了96ms

如果使用hash,减到48ms

map使用红黑树实现,查找速度是log(n)级别;

hash查找速度基本和数据量大小无关。

不过并非任何时候hash都比map快,因为hash需要hash函数,构造会比较慢。

另外,本题可以对数组进行排序,之后判断相邻元素是否有相同的即可。

0 0
原创粉丝点击