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 ≤ a[i] ≤ n】非常耐人寻味,要善于加以利用(结合数组的特性)。
class Solution {
public:
vector<int> findDuplicates(vector<int>& nums) {
vector<int>::iterator it;
vector<int> newNums;
for(it=nums.begin();it!=nums.end();it++){
if(nums[abs(*it)-1]>0)
nums[abs(*it)-1]*=-1;
else
newNums.push_back(abs(*it));
}
return newNums;
}
};
public class Solution {
public List<Integer> findDuplicates(int[] nums) {
List<Integer> res = new LinkedList<>();
for(int i=0; i<nums.length; i++){
int n = Math.abs(nums[i]);
if(nums[n-1]<0)
res.add(n);
else
nums[n-1]*=-1;
}
return res;
}
}