[LeetCode] Find the Duplicate Number

287. Find the Duplicate Number

Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive.

There is only one repeated number in nums, return this repeated number.

  • new solution update 2022.02.25
1
2
3
4
5
6
7
8
9
10
11
class Solution {
public:
int findDuplicate(vector<int>& nums) {
for(auto n : nums) {
int index = abs(n) - 1;
if(nums[index] < 0) return abs(n);
nums[index] = -nums[index];
}
return -1;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
int findDuplicate(vector<int>& nums) {
unordered_set<int> s;
for(auto& n : nums) {
if(s.count(n)) return n;
s.insert(n);
}
return -1;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2021/05/16/PS/LeetCode/find-the-duplicate-number/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.