Acwing 14. 不修改數組找出重複的數字

題目地址  https://www.acwing.com/problem/content/description/15/數組

來源:劍指Offerspa

給定一個長度爲 n+1n+1 的數組nums,數組中全部的數均在 1n1∼n 的範圍內,其中 n1n≥1。code

請找出數組中任意一個重複的數,但不能修改輸入的數組。xml

樣例

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

返回 23

 

題解 blog

一個典型的哈希例題 ip

代碼以下get

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;
    }
};
相關文章
相關標籤/搜索