题目:给一个未排序的n个元素的数组,数组中所有的元素都在1到n之间,删除数组中所有冗余的数字
例如: {1,3,2,3,2,6,4,3}
删除冗余后数组: {1,2,3,4,6}
方法一:可以利用哈希表的方法,将所有的数字映射到a[n],如果整数i出现过,则a[i-1]++,最后输出
所有a[i] >0的整数即可。这个方法需要o(n)的空间和o(n)的时间。
方法二:如果要求0(1)的空间复杂度和O(n)的时间复杂度怎么做呢?
可以对序列中的元素做标记,如果某个位置上的数出现过就将它变为负数。例如上上面的数组中的3
seq[abs(seq[1]) - 1] = -abs(abs(seq[1])-1);这样就很好的利用了数组的位置信息。
参照:http://blog.csdn.net/yysdsyl/archive/2009/06/30/4311031.aspx的代码
- void RemoveAllDuplicates(int seq[], int n)
- {
- // if element e exists in the array, make index (e-1) negative
- for(int i = 0; i < n; i++)
- seq[abs(seq[i]) - 1] = -abs(seq[abs(seq[i]) - 1]);
- // if index (e-1) is negative, print element e
- cout<<endl;
- for(int i = 0; i < n; i++)
- if(seq[i] < 0)
- cout<<i + 1<<"/t";
- cout<<endl;
- }
http://www.careercup.com/question?id=14990323
Given An Array with N integer with values ranging from 1 to N. there is only one duplicate in the Array.
Find out Duplicate value.
i.e.
A = { 10,6,3,4,7,5,2,4,9,1}