zoukankan      html  css  js  c++  java
  • 把一个整形数组中重复的数字去掉

    请把一个整形数组中重复的数字去掉。例如: 
    1,   2,   0,   2,   -1,   999,   3,   999,   88 
    答案应该是: 

    1,   2,   0,   -1,   999,   3,   88


    思路:一次遍历数组找出绝对值最大的数,以便确定哈希表的大小。

    第二次遍历数组,当遇到第一次出现的数,则放入应该放的位置(仍在原数组中),如果重复则不放入。


    VS2010中测试正确代码如下:


    #include<iostream>
    using namespace std;
    
    typedef struct Info
    {
    	Info():isPos(0),isNeg(0){}
    	bool isPos;
    	bool isNeg;
    }HashTable;
    
    int main()
    {
    	int a[] = {1,2,0,2,-1,999,3,999,88,-1,2,2,2,-1,4,4,44,444,44,444,4444};
    	int max = INT_MIN;//#define INT_MIN     (-2147483647 - 1) /* minimum (signed) int value */
    
    	for(int i=0;i<sizeof(a)/sizeof(a[0]);++i)
    	{
    		cout<<a[i]<<" ";
    	}
    	cout<<endl;
    
    	for(int i=0;i<sizeof(a)/sizeof(a[0]);++i)
    	{
    		if(abs(a[i])>max)
    			max = abs(a[i]);
    	}
    
    	HashTable* hash = new HashTable[max+1];
    	
    	int toReplace=0;
    	 for(int current=0;current<sizeof(a)/sizeof(int);++current)
    	 {
    		 if(hash[abs(a[current])].isPos==0 && hash[abs(a[current])].isNeg==0)
    		 {
    			 if(a[current]>0 || a[current] == 0)
    				 hash[abs(a[current])].isPos=1;
    			 if(a[current]<0)
    				 hash[abs(a[current])].isNeg=1;
    
    			 a[toReplace] = a[current];
    			 toReplace++;
    		 }
    		 else
    		 {
    			 //确定重复
    			 if(hash[abs(a[current])].isPos==1 && (a[current]>0 || a[current]==0))
    				continue ;
    			  if(hash[abs(a[current])].isNeg==1 && a[current]<0)
    				continue ;
    			  else
    			  {//不重复
    				   if(a[current]>0 || a[current] == 0)
    						hash[abs(a[current])].isPos=1;
    					 if(a[current]<0)
    						 hash[abs(a[current])].isNeg=1;
    				   
    					 a[toReplace] = a[current];
    					toReplace++;
    			  }
    		 }
         }
    
    	 for(int i=0;i<toReplace;++i)
    	{
    		cout<<a[i]<<" ";
    	}
    	cout<<endl;
    
    	system("pause");
    	return 0;
    }


    运行结果截图如下:


  • 相关阅读:
    png 图片的缩放
    数据结构>图的最短路径
    2007年7月25日在博客园的排名上升到前400名
    C# 汉字转拼音(全拼)
    修改 Linux 主机名
    C# 事件的继承
    一个实现了 IDisposable 接口的基类
    Windows 防火墙上也有端口映射功能
    网上邻居不能访问的问题
    令网站提速的7大秘方
  • 原文地址:https://www.cnblogs.com/dyllove98/p/3237059.html
Copyright © 2011-2022 走看看