442. Find All Duplicates in an Array
问题描述:
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:
Input: [4,3,2,7,8,2,3,1] Output: [2,3]
解题思路:
因为数组中的数字都限制在[1,n]范围之内,我们可以将每一个数字n安排到n-1的位置:
如果其对应位置上已经有了与之相匹配的数字,则代表该数字重复。
代码:
class Solution { public: vector<int> findDuplicates(vector<int>& nums) { vector<int> ret; set<int> s; for(int i = 0; i < nums.size(); i++){ while(nums[i]-1 != i){ if(nums[nums[i]-1] != nums[i]){ swap(nums[nums[i]-1], nums[i]); }else{ if(s.count(nums[i]) == 0){ s.insert(nums[i]); ret.push_back(nums[i]); } break; } } } return ret; } };
更快的解法:
思路是一样的,不过没用set辅助,达到要求
class Solution { public: vector<int> findDuplicates(vector<int>& nums) { vector<int> res; int i = 0; while (i < nums.size()) { if (nums[i] != nums[nums[i]-1]) swap(nums[i], nums[nums[i]-1]); else i++; } for (i = 0; i < nums.size(); i++) { if (nums[i] != i + 1) res.push_back(nums[i]); } return res; } };