217. 存在重复元素

给定一个整数数组,判断是否存在重复元素。

如果任意一值在数组中出现至少两次,函数返回 true 。如果数组中每个元素都不相同,则返回 false 。
示例 1:

输入: [1,2,3,1]
输出: true

示例 2:

输入: [1,2,3,4]
输出: false

示例 3:

输入: [1,1,1,3,3,4,3,2,4,2]
输出: true

代码:
先将其排序,判断元素是否和下一个元素相等:时间复杂度:NlogN 空间复杂度:logN

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

2.将元素插入到哈希表中,插入元素到哈希表中元素在表中,说明存在重复的元素。

class Solution {
public:
    bool containsDuplicate(vector<int>& nums) {
        unordered_set<int> s;
        //迭代容器中所有的元素,x是元素值,不是地址
        for (int x: nums) {
        //如果在s里面找到了该元素,说明是重复元素(s.find(x) != s.end()这里s.find(x)返回的是地址,返回的地址不等于s.end()说明找到了该元素)
            if (s.find(x) != s.end()) {
                return true;
            }
            s.insert(x);
        }
        return false;
    }
};

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/contains-duplicate

备注:for (auto x : nums)作用就是迭代容器中所有的元素,每一个元素的临时名字就是x,等同于下边代码
等价于for (vector<int>::iterator iter = nums.begin(); iter != nums.end(); iter++)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值