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?
这个题目的要求是,只读,并且不准申请额外空间,那么如何标记成了一个重要的问题,恰好题目中最多只会出现两次,因此找到元素后,利用负号进行标记是个最佳的方式,代码如下
class Solution {
public:
vector<int> findDuplicates(vector<int>& nums) {
int i = 0;
int pos = 0;
vector<int> final_num;
for (; i < nums.size(); i++)
{
pos = abs(nums[i]) - 1;
if (nums[pos] < 0)
{
final_num.push_back(abs(nums[i]));
}
else
{
nums[pos] = -nums[pos];
}
}
return final_num;
}
};
本文介绍了一种在不使用额外空间的情况下找出数组中重复元素的方法。利用数组元素值的特点,通过将出现过的元素位置上的数值标记为负数来实现查找,确保了算法的空间复杂度为O(1),时间复杂度为O(n)。
839

被折叠的 条评论
为什么被折叠?



