|
| 1 | +#include <bits/stdc++.h> |
| 2 | + |
| 3 | +using namespace std; |
| 4 | + |
| 5 | +class Solution { |
| 6 | +public: |
| 7 | + // using hash table to store the number of times of each number |
| 8 | + // Time complexity: O(n) |
| 9 | + // Space complexity: O(n) |
| 10 | + int findDuplicateUsingSet(vector<int>& nums) { |
| 11 | + set<int> s; |
| 12 | + int res = 0; |
| 13 | + for (int i = 0; i < nums.size(); i++) { |
| 14 | + if (s.find(nums[i]) != s.end()) { |
| 15 | + res = nums[i]; |
| 16 | + break; |
| 17 | + } else { |
| 18 | + s.insert(nums[i]); |
| 19 | + } |
| 20 | + } |
| 21 | + return res; |
| 22 | + } |
| 23 | + |
| 24 | + // Floyd's Algorithm |
| 25 | + // Time complexity: O(n) |
| 26 | + // Space complexity: O(1) |
| 27 | + int findDuplicate(vector<int>& nums) { |
| 28 | + int slow = nums[0], fast = nums[0]; |
| 29 | + do { |
| 30 | + slow = nums[slow]; |
| 31 | + fast = nums[nums[fast]]; |
| 32 | + } while (slow != fast); |
| 33 | + fast = nums[0]; // reset the fast pointer to the beginning of the array |
| 34 | + while(slow != fast) { |
| 35 | + slow = nums[slow]; |
| 36 | + fast = nums[fast]; |
| 37 | + } |
| 38 | + return slow; |
| 39 | + } |
| 40 | +}; |
| 41 | + |
| 42 | +int main() { |
| 43 | + Solution sol; |
| 44 | + vector<int> test1 = { 1,3,4,2,2 }; |
| 45 | + vector<int> test2 = { 3,1,3,4,2 }; |
| 46 | + vector<int> test3 = { 1,1 }; |
| 47 | + vector<int> test4 = { 1,1,2 }; |
| 48 | + cout<<sol.findDuplicate(test1)<<endl; |
| 49 | + cout<<sol.findDuplicate(test2)<<endl; |
| 50 | + cout<<sol.findDuplicate(test3)<<endl; |
| 51 | + cout<<sol.findDuplicate(test4)<<endl; |
| 52 | + return 0; |
| 53 | +} |
0 commit comments