Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements that appear twice in this array.
Could you do it without extra space and in O(n) runtime?
Example:
1 2 3 4 5 |
<b>Input:</b> [4,3,2,7,8,2,3,1] <b>Output:</b> [2,3] |
1 2 3 4 5 6 7 8 9 10 11 12 13 |
class Solution { public: vector<int> findDuplicates(vector<int>& nums) { vector<int> ans; for(auto num : nums) { int index = abs(num)-1; if (nums[index] < 0) ans.push_back(index+1); nums[index]*=-1; } return ans; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment