【题目】
找出数组中重复的数字。在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。
来源:leetcode
链接:https://leetcode-cn.com/problems/shu-zu-zhong-zhong-fu-de-shu-zi-lcof/
【示例1】
输入:
[2, 3, 1, 0, 2, 5, 3]
输出:2 或 3
【限制】
2 <= n <= 100000
【代码】
【set】
class Solution {
public:
set<int> s;
int findRepeatNumber(vector<int>& nums) {
for(auto x:nums)
if(s.count(x))
return x;
else
s.insert(x);
return -1;
}
};
【map】
class Solution {
public:
map<int,int> m;
int findRepeatNumber(vector<int>& nums) {
for(auto x:nums)
m[x]++;
for(auto x:m)
if(x.second>1)
return x.first;
return -1;
}
};
【排序】
class Solution {
public:
int pre=-1;
int findRepeatNumber(vector<int>& nums) {
sort(nums.begin(),nums.end());
for(auto x:nums){
if(pre==x)
return x;
pre=x;
}
return -1;
}
};
【哈希法 时间换空间】
class Solution {
public:
int hashnum[100000]={0};
int findRepeatNumber(vector<int>& nums) {
for(auto x:nums){
if(hashnum[x])
return x;
hashnum[x]++;
}
return -1;
}
};