题意
判断一个数组中是否有元素出现了2次或以上。
思路
用一个unordered_set记录一下就好。
代码
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
unordered_set<int> has;
for (auto x : nums) {
if (has.count(x)) return true;
has.insert(x);
}
return false;
}
};

本文介绍了一种使用unordered_set数据结构来高效判断数组中是否存在重复元素的方法。通过遍历数组并将元素插入到unordered_set中,若插入失败则表明该元素已存在,从而实现快速检测。
&spm=1001.2101.3001.5002&articleId=55225081&d=1&t=3&u=da534704d24d429585fa70cebc0c28d1)
175

被折叠的 条评论
为什么被折叠?



