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; } };
|