LeetCode 442 Find All Duplicates in an Array
Train of thought
In this case, the value of the current element is used as the index of the next element. 287 Find the Duplicate Number 448 Find All Numbers in an Array
code
class Solution { public: vector<int> findDuplicates(vector<int>& nums) { vector<int> rs; int index; for (int i = 0; i < nums.size(); ++i) { index = abs(nums[i]) - 1; if (nums[index] < 0) rs.push_back(index + 1); else nums[index] = -nums[index]; } return rs; }};Copy the code