JZ3 数组中重复的数字

JZ3 数组中重复的数字

题目链接:

数组中重复的数字_牛客题霸_牛客网 (nowcoder.com)

完整解答:

set::count()是C++ STL中的内置函数,它返回元素在集合中出现的次数。由于set容器仅包含唯一元素,因此只能返回1或0。

  • 用法:set_name.count(element)
  • 参数:该函数接受一个强制性参数element,该元素指定要返回其计数的元素。
  • 返回值:该函数返回1或0,因为该集合仅包含唯一元素。如果设置的容器中存在该值,则返回1。如果容器中不存在它,则返回0。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param numbers int整型vector
* @return int整型
*/
int duplicate(vector<int>& numbers) {
// write code here
set<int> s;
for(int i=0;i<numbers.size();i++){
if(s.count(numbers[i])>0) //此元素重复,则返回
return numbers[i];
else
s.insert(numbers[i]); //不重复则加入集合
}
return -1;
}
};

参考资料:

(64条消息) 【c++】set.count()用法_杳杳捞到月亮了吗的博客-CSDN博客_c++set count


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!