题目地址 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; } };