剑指 Offer 03. 数组中重复的数字 哈希

地址 https://leetcode-cn.com/problems/shu-zu-zhong-zhong-fu-de-shu-zi-lcof/

找出数组中重复的数字。

在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。

示例 1:
输入:
[2, 3, 1, 0, 2, 5, 3]
输出:23 
 

限制:
2 <= n <= 100000

 

解答:

算法1  直觉上直接排序 然后遍历查看i和i+1是否相同

时间复杂度 O(nlogn)

class Solution {
public:
    int findRepeatNumber(vector<int>& nums) {
        sort(nums.begin(),nums.end());
        //注意边界
        for(int i =0; i<nums.size()-1;i++){
            if(nums[i]==nums[i+1]) return nums[i];
        }
        //不可能得达这里
        return -1;
    }
};

算法2 开个map或者set进行记录已经搜索到的数字 遍历数组查询是否有相同的数字已经存在,如果存在则说明该数字重复了。(小技巧:开数组进行哈希更快)

由于不必排序 哈希的复杂度为O(1)

整体时间复杂度 O(n)

class Solution {
public:
    int arr[100010];
    int findRepeatNumber(vector<int>& nums) {
        for(auto& e:nums){
            if(arr[e]!=0) return e;
            else arr[e]=1;
        }
        
        return -1;
    }
};

 

posted on 2021-02-06 15:15  itdef  阅读(122)  评论(0编辑  收藏  举报

导航