问题:
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]
分析: // when find a number i, flip the number at position i-1 to negative.
// if the number at position i-1 is already negative, i is the number that occurs twice.
简单的讲,是利用了一个哈希表,把出现一次的数字变为负数,第二次又出现时就返回。把值作为下标值.
代码
/**
* Return an array of size returnSize.
* Note: The returned array must be malloced, assume caller calls free().
/
int findDuplicates(int nums, int numsSize, int* returnSize) {
returnSize=0;
int re=NULL;
int index;
for(int i=0;i<numsSize;i++)
{
index=abs(nums[i])-1;
if(nums[index]>0) nums[index]=-1;
else {
(returnSize)++;
re=(int )realloc(re,sizeof(int)(returnSize));
re[(returnSize)-1]=index+1;
}
}
return re;
}