217. Contains Duplicate

来源:互联网 发布:全民微信时代知乎 编辑:程序博客网 时间:2024/05/17 03:23

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.

方法一:

思路很简单,可以先排序,这样重复数字集中到一起,判断前后是否有重复即可,复杂度就是O(nlogn)。

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

方法二:

最直接的哈希表运用,建立hash map,线性检索一遍数组,如果该数字在表中不存在,插入,存在,证明重复。复杂度O(n)。

bool containsDuplicate(vector<int>& nums) {    unordered_map<int, int> myhash;    for (int i = 0; i < nums.size(); i++) {        if (myhash.find(nums[i]) == myhash.end()) {            myhash[nums[i]]++;        }        else           return true;    }    return false;}

注意,这种理论复杂度并不能完全代表leetcode的运行时间,因为一方面,作为初学者的代码,通常算法上意思对了,但代码也是粗糙未经优化的。另一方面,leetcode的测试用例太少,有误差。所以大家不用太认真比较运行时间。当然,最起码每道题多想几种方法开阔下思路,至少保证能有一个超过50%的code,这点还是应该的。

0 0
原创粉丝点击