【leetCode】 442. Find All Duplicates in an Arra

问题:

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;
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容