删除整形数组中的冗余整数

504 篇文章 0 订阅

转自出处


题目:给一个未排序的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的代码

[cpp]  view plain copy
  1. void RemoveAllDuplicates(int seq[], int n)  
  2. {  
  3.     // if element e exists in the array, make index (e-1) negative   
  4.     for(int i = 0; i < n; i++)   
  5.         seq[abs(seq[i]) - 1] = -abs(seq[abs(seq[i]) - 1]);   
  6.   
  7.     // if index (e-1) is negative, print element e   
  8.     cout<<endl;  
  9.     for(int i = 0; i < n; i++)   
  10.         if(seq[i] < 0)   
  11.             cout<<i + 1<<"/t";   
  12.     cout<<endl;  
  13. }  

 

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}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值