Spurs

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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 .. n] 范围内,要求找出数组中重复2次的元素.

思路为:针对元素值 a 来说,a - 1作为索引对应了另一个元素,若为正数,表明 a 第一次出现,此时在 A[a-1] 处做个标记,改成负数,表示元素 a 已经到此一游过,若 A[a-1] 为负数,表明a第二次出现,应该输出到结果集合中.

例子: 顺序扫描数组,假设扫描到第一个2, 我们查看 indx = 2 - 1 = 1的元素是否为 -3, 若为-3,表面 2 是重复元素, 否则将 A[indx = 1]设置为-3.

人家思路,自己代码:
\(O(n)\) time, \(O(1)\) extra space.

vector<int> findDuplicates(vector<int>& A) {
	const int n = A.size();
	vector<int> res;

	for (int i = 0; i < n; i++) {
		int indx = abs(A[i]) - 1;
		if (A[indx] < 0) res.push_back(abs(A[i]));
		else A[indx] = 0 - A[indx];
	}

	return res;
}
posted on 2017-08-21 11:55  英雄与侠义的化身  阅读(114)  评论(0编辑  收藏  举报