Skip to content

Commit a6f3c2c

Browse files
Merge pull request #386 from ys13579/master
FindDuplicate.cpp
2 parents 8d0a788 + 9c5d241 commit a6f3c2c

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

C++/FindDuplicate.cpp

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
2+
//Given numbers from 1 to n, find the duplicate number in 0(n) time complexity and O(1) space complexity
3+
4+
5+
class Solution {
6+
public:
7+
int findDuplicate(vector<int>& nums) {
8+
//Define an empty set
9+
set<int> con;
10+
set<int>::iterator it;
11+
12+
//Iterate over the array
13+
for(int i=0;i<nums.size();i++){
14+
it = con.find(nums[i]);
15+
16+
//Number already present in set
17+
if(it != con.end())
18+
return nums[i];
19+
else
20+
con.insert(nums[i]);
21+
}
22+
23+
};
24+
25+
int main() {
26+
27+
vector<int> nums = {1, 2, 3, 7, 5, 6, 7}
28+
29+
int ret = Solution().findDuplicate(nums);
30+
cout << ret << endl;
31+
32+
return 0;
33+
}

0 commit comments

Comments
 (0)