LeetCode-217-Contains Duplicate-E(检验是否有重复数字)

本文介绍了一种高效检测整型数组中是否存在重复元素的方法。通过使用无序集合(unordered_set),可以实现平均时间复杂度为O(n)的算法,显著提高了查找效率。文中给出了具体的C++代码实现,并对比了其他几种解决方案。

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.

Example 1:

Input: [1,2,3,1]
Output: true

Example 2:

Input: [1,2,3,4]
Output: false

Example 3:

Input: [1,1,1,3,3,4,3,2,4,2]
Output: true

解决方案:
一:双层循环,时间复杂度太高,放弃
二:先排序后再单层遍历,时间复杂度nlogn,还是偏高
三:使用unorder_set,代码如下

bool containsDuplicate(vector<int>& nums) {
        unordered_set<int>set;
        for(auto num:nums){
            if(set.find(num)!=set.end())
                return true;
            set.insert(num);
        }
        return false;
    }
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值