读书人

去掉一个数组的反复元素

发布时间: 2012-09-02 21:00:34 作者: rapoo

去掉一个数组的重复元素
去掉一个数组的重复元素
N个元素的数组,最好的情况是只要遍历一次就能找出所有重复,这样时间复杂度是O(n).我的第一反应是为每个元素算hash,如果有重复的元素,肯定能找到冲突。如果在Java中,这太好办了,HashSet中有一个add方法,如果该方法返回的是false,那肯定是发现了重复的元素。但是在js中却没有这样现成的工具。但是可以考虑把js中的object来当做hash表使用。

Array.prototype.removeRepeat=function(){       var hashMap={};       for(var i in this){           if(typeof this[i]!=='function'){               if(hashMap[this[i]]===undefined)                   hashMap[this[i]]=1;               else{                   hashMap[this[i]]++;               }           }       }              var arr=[];       for(var i in hashMap){           if(hashMap[i]==1){               arr.push(i);           }       }       return arr;   }   var array=[1,null,'cad',3,'abg',3,null,'abg'];   var hashMap=array.removeRepeat();   console.log(hashMap);

如果该数组仅含有数字或字符串,那么可以用相对比较简单的处理:先把数组排序,再两两相邻比较,重复的就除去。基于这个想法,写了个如下的实现:

Array.prototype.removeRepeat=function(){       var arr=new Array();       for(var i in this){           arr[i]=this[i];       }       arr.sort();        for(var i=0;i<arr.length;i++){           var item=arr[i];           for(var j=i+1;j<arr.length;j++){               if(item===arr[j]){                   arr.splice(j--,1);                }           }       }       return arr;   }   var array=[1,5,'cad',3,4,'abg',2,3,5,'gba','abg'];   var arr=array.removeRepeat();   console.log(arr); 


按照格式:xxxx年xx月xx日xx时xx分xx秒动态显示时间
要求不足10的补0

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">   <html xmlns="http://www.w3.org/1999/xhtml">   <head>   <meta http-equiv="Content-Type" content="text/html; charset=utf-8">   <title>test</title>   <script type='text/javascript'>Date.prototype.toSpecifiedFormat=function(){       var year=this.getFullYear();       var month=this.getMonth()+1;       var date=this.getDate();       var hours=this.getHours();       var minutes=this.getMinutes();       var seconds=this.getSeconds();        return  year+'年'+               ((month<10)?'0'+month:month)+'月'+               ((date<10)?'0'+date:date)+'日'+               ((hours<10)?'0'+hours:hours)+'时'+               ((minutes<10)?'0'+minutes:minutes)+'分'+               ((seconds<10)?'0'+seconds:seconds)+'秒';   }     setInterval(function(){       document.getElementById('time').value=new Date().toSpecifiedFormat();   },1000)    </script>   </head>   <body>       <input type='text' id='time' style='width:200px;' >   </body>   </html>  

R:http://driftcloudy.iteye.com/blog/783048

读书人网 >软件架构设计

热点推荐