文章博客

技术团队文档示例


第五天:数组去重,排序

<blockquote> <p>思路:对数组去重 + 排序 = 排序后的数组</p> </blockquote> <pre><code>//#第一题 let arr= [3,5,7,2,4,5] let arr1 = [...new Set(arr)]; //数组去重 console.log(arr1) //[3, 5, 7, 2, 4] let sort = arr1.sort().map((item) =&gt;{ return item; }) console.log(sort) //[2, 3, 4, 5, 7] //将数组扁平化并去除其中重复数据,最终得到一个升序且不重复的数组 // #第二题: var arr = [ [1, 2, 2], [3, 4, 5, 5], [6, 7, 8, 9, [11, 12, [12, 13, [14] ] ] ], 10] Array.prototype.falt = function() { return [].concat(...this.map(item =&gt; (Array.isArray(item) ? item.falt() : [item]))); } Array.prototype.unique = function() { return [...new Set(this)] } const sort = (a, b) =&gt; a - b; console.log(arr.falt().unique().sort(sort)); // [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 ]</code></pre> <h4>数组去重1</h4> <hr /> <p>数组去重,要求时间复杂度O(nlogn) 空间复杂度O(1)</p> <pre><code>function uniqueArray(list) { // 1 1 2 2 3 4 // 当然你可以自己写快排等nlogn的算法 list.sort(); // 剩下的代码和leetcode26题一摸一样 const size = list.length; let slowP = 0; for (let fastP = 0; fastP &lt; size; fastP++) { if (list[fastP] !== list[slowP]) { slowP++; list[slowP] = list[fastP]; } } return list.slice(0, slowP + 1); } console.log(uniqueArray([1, 1, 2, 2, 3, 4])); console.log(uniqueArray([1, 1, 6, 7, 9, 9, 8, 2, 2])); console.log(uniqueArray(["a", "c", "b", "z", "A", "K", "d", "D", "a"]));</code></pre> <h4>数组去重2</h4> <hr /> <pre><code>var a = [1,2,3,4,5,6,7,6,5,4,3,2,1]; //去重 -- 用object的方法 // var istrue = { // "1" : 1 // } let len = a.length; var obj={}; var arr=[]; for(var i =0;i&lt;len;i++){ if(!obj[a[i]]){ obj[a[i]] =true; arr.push(a[i]) } } console.log(arr) //[1, 2, 3, 4, 5, 6, 7]</code></pre> <h4>数组去重3</h4> <hr /> <p>新建数组 用indexOf比较两个数组中的值是否包含</p> <pre><code>let arr= [3,5,7,2,4,5,5]; var newArr = []; for(var i =0;i&lt;arr.length;i++){ if(newArr.indexOf(arr[i]) === -1){ newArr.push(arr[i]) } } newArr.sort() console.log(newArr)//[2, 3, 4, 5, 7]</code></pre> <h4>数组去重排序4</h4> <ul> <li>1.排序sort</li> <li>2.以第一位为基础, =第一位则放进数组 !== &amp;&amp; 后一位和前一位对比 放进数组</li> </ul> <pre><code> let arr = [1, 1, 2, 2, 5, 5, 'a', 'a', '3', '3'] arr = arr.sort(); let realarr = []; for (let i = 0; i &lt; arr.length; i++) { if (i == 0) { realarr.push(arr[i]) } else if (i !== 0 &amp;&amp; arr[i] !== arr[i - 1]) { realarr.push(arr[i]) } } console.log(realarr)</code></pre> <h4>数组排序</h4> <h5>1. 冒泡排序</h5> <pre><code>function bubble_sort(arr){ for(var i=0;i&lt;arr.length-1;i++){ for(var j=0;j&lt;arr.length-i-1;j++){ if(arr[j]&gt;arr[j+1]){ var swap=arr[j]; arr[j]=arr[j+1]; arr[j+1]=swap; } } } } var arr=[3,1,5,7,2,4,9,6,10,8,8]; bubble_sort(arr); console.log(arr); //[1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 10]</code></pre>

页面列表

ITEM_HTML