題目地址 https://www.acwing.com/problem/content/description/15/數組
來源:劍指Offerspa
給定一個長度爲 n+1n+1 的數組nums
,數組中全部的數均在 1∼n1∼n 的範圍內,其中 n≥1n≥1。code
請找出數組中任意一個重複的數,但不能修改輸入的數組。xml
給定 nums = [2, 3, 5, 4, 3, 2, 6, 7]。 返回 2 或 3。
題解 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; } };