Home > Article > Web Front-end > Introducing the dichotomy method in js and the example code for deduplication
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> </body> <script type="text/javascript"> var arr =[1,2,3,4,5,6,7,8,9,0,8,5,5,4,3]; //创建一个数组 function findInArr(arr,n){ //循环数组中的每一项如果它的每一个i项与n相等就返回继续执行 for (var i=0;i<arr.length;i++){ if (arr[i] == n){ return true; } } return false; } function removeDup(arr,s,e){ // 判断这个数组,的开始顺序,和这个数组是不是首项和尾项相等 if (s>e) { return false; } else if(s==e){ return [arr[s]]; } // 将数组进行二分,找到中间项,将数组分为两部分 var c= Math.floor((s+e)/2); var l = removeDup(arr,s,c); var r = removeDup(arr,c + 1,e); for (var i=0;i< r.length; i++) { if (!findInArr(l,r[i])) { l.push(r[i]) } } return l; } console.log(removeDup(arr,0,arr.length-1)) </script> </html>
Algorithms are a wonderful thing, and I hope we can communicate more with them.
The above is the detailed content of Introducing the dichotomy method in js and the example code for deduplication. For more information, please follow other related articles on the PHP Chinese website!