Acwing 14. 不修改数组找出重复的数字

题目地址  https://www.acwing.com/problem/content/description/15/

来源:剑指Offer

给定一个长度为 n+1n+1 的数组nums,数组中所有的数均在 1n1∼n 的范围内,其中 n1n≥1。

请找出数组中任意一个重复的数,但不能修改输入的数组。

样例

给定 nums = [2, 3, 5, 4, 3, 2, 6, 7]。

返回 23

 

题解 

一个典型的哈希例题 

代码如下

class Solution {
public:
    int duplicateInArray(vector<int>& nums) {
        unordered_map<int,int> h;
        for(auto& e:nums){
            h[e] +=1;
            if(h[e] > 1)
                return e;
        }
        
        return -1;
    }
};

 

posted on 2019-07-17 21:34  itdef  阅读(163)  评论(0编辑  收藏  举报

导航