解題思路
利用哈希表解決,時間複雜度o(n)
代碼
class Solution {
public:
int findRepeatNumber(vector<int>& nums) {
unordered_map<int, int> hashMap(nums.size());//需要初始化大小
for (vector<int>::iterator it=nums.begin();it!=nums.end();it++)
{
if (hashMap.find(*it)==hashMap.end())//如果該數字不存在
{
hashMap[*it] = 1;
}
else//存在該數字,則直接返回
{
return *it;
}
}
return -1;//這裏不能省略,否則會編譯出錯
}
};