题目描述:
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]
题目分析:
首先这是一道看起来非常简单的题目,只是加了一些限制条件,不使用额外的空间和算法的时间复杂度为O(n)。
首先先考虑复杂度O(n),意味着数组中每个元素只能访问一次,很容易就可以联想到桶排序的方法,创建一个新数组B,将原数组A的元素数值i作为新的数组B的下标保存下来,如在数组A中的i出现表示为B[i]=1。
由于不能创建新的空间,因此只能改变原数组中的元素值。我们注意到题目中1 ≤ a[i] ≤ n (n = size of array)这个条件,因此可以按照桶排序的方法将数组A中的i出现对A[i-1]这个元素进行标识,最简单的方式即为取反,所以每当元素i出现一次,A[i-1]=-A[i-1]。因此在访问每个元素时要使用绝对值进行访问。
代码:
#include <cmath>
class Solution {
public:
vector<int> findDuplicates(vector<int>& nums) {
vector<int> result;
for (int i = 0; i < nums.size(); i++) {
nums[abs(nums[i])-1] = -nums[abs(nums[i])-1];
if (nums[abs(nums[i])-1] > 0)
result.push_back(abs(nums[i]));
}
return result;
}
};