
题目地址 https://www.acwing.com/problem/content/description/15/
来源:剑指Offer
给定一个长度为 n+1n+1 的数组nums
,数组中所有的数均在 1∼n1∼n 的范围内,其中 n≥1n≥1。
请找出数组中任意一个重复的数,但不能修改输入的数组。
样例
给定 nums = [, , , , , , , ]。 返回 或 。
题解
一个典型的哈希例题
代码如下
class Solution {
public:
int duplicateInArray(vector<int>& nums) {
unordered_map<int,int> h;
for(auto& e:nums){
h[e] +=;
if(h[e] > )
return e;
} return -;
}
};