Givenan array of integers, 1 ≤ a[i] ≤ n (n =size of array), some elements appear twice andothers appear once.
Findall the elements that appear twice in this array.
Couldyou do it without extra space and in O(n) runtime?
Example:
Input:
[4,3,2,7,8,2,3,1]
Output:
[2,3]
这题要求给你一个数组,要你求出这个数组所有出现过两次的数字,并且要求时间复杂度不要超过O(n),空间复杂度不要超过O(1)
这里有两个非常重要的思路,就是,要求空间复杂度不要超过O(1),其实就是要求你定义的常数要是有限多个,并且不能定义长度随着n增大而增大的数组,其实就是不能定义额外的数组,但是你可以使用一开始给你的数组,这样也是符合规矩的,比如这一题一开始给你一个num数组,你就可以使用这个数组,而不会触犯规矩
其二就是其实只要添加一个bool数组就能轻松解决这一题,但是题目要求不能定义额外的数组,因此我们可以利用原数组,由于原数组每一个数都是正数,所以我们可以使用原数组每一个数字的正负号来代替bool数组的功能,这样就能够轻松在O(n)的时间内得到结果
class Solution {
public:
vector<int> findDuplicates(vector<int>&nums) {
vector<int>result;
for (int i = 0;i < nums.size(); i++)
{
intindex = abs(nums[i]) - 1;
if(nums[index] < 0)
result.push_back(index+1);
else
nums[index]= -nums[index];
}
return result;
}
};