[剑指Offer]3.数组中重复的数字

题目


找出数组中重复的数字。
在一个长度为n的数组中的所有数字都在0~n-1的范围内。数组中某些数字是重复的,但是不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数组。例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是重复的数字2或者3。

代码


#include <iostream>
#include <vector>
#include <map>
using namespace std;
class Solution
{
public:
    bool hasRepeatNums(vector<int> nums)
    {
        map<int, int> hashtable;
        for (auto i : nums)
            ++hashtable[i];
        for (auto i:hashtable)
        {
            if (i.second>1)
            {
                return true;
            }
        }
        return false;
    }
};

思路


空间换时间的策略,时间复杂度为O(n),空间复杂度为O(n)

https://github.com/li-zheng-hao
原文地址:https://www.cnblogs.com/lizhenghao126/p/11053671.html