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

时间:2023-03-09 21:53:43
Acwing 14. 不修改数组找出重复的数字

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