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?
二、输入输出
Input:
[4,3,2,7,8,2,3,1]
Output:
[2,3]
三、解题思路
- 还有一道是找没有出现的数字的题448. Find All Numbers Disappeared in an Array
- 这两道题很像,难点在于时间复杂度为o(n) 空间复杂度为o(1). 快速排序的最好时间复杂度是o(nlogn) 最差是o(n2) 所以不能排序,而且需要在原来的数组上进行修改。
- 这里面存在一个映射关系,即第i个元素(从0开始) 对应的值为(i+1) 这样正好将1-n从小到大的排列到数组上。
- 核心思想就是:我们把遍历到的nums[i] 对应的位置的值设置为原值的相反数,来表示这个nums[i]是否已经出现过了,比如:
curVal = nums[i]
我们期望他在的位置是expectIndex = nums[i] - 1
然后把expectIndex
位置的数设置为负数nums[expectIndex] = - nums[expectIndex]
, 来表示我们刚刚搜索过nums[i]
了,这个数字是存在的。 - 如果是找重复出现的数字,那么只需要判断
nums[expectIndex]
是不是负的就行了。是负的,说明之前出现过expectIndex + 1
这个值,现在又出现了,所以重复了。 - 如果是找没有出现的数字,只需要重新遍历一遍数组,哪些index对应的nums[index]为正,则说明对应index的值
index+1
没有出现过,如果出现过他应该被我们设置为负的了。
class Solution {
public:
vector<int> findDuplicates(vector<int>& nums) {
int n = nums.size();
vector<int> ret;
for (int i = 0; i < n; ++i) {
int curVal = abs(nums[i]);
int expectIndex = curVal - 1;
if (nums[expectIndex] > 0)
nums[expectIndex] = - nums[expectIndex];
else
ret.push_back(curVal);
}
return ret;
}
};