怎么以O(n)的复杂度实现数组的去重?(js)

问题描述:

如何以 `O(n)` 的时间复杂度实现字符序列的去重,如对以下数组去重
[1, 'a', '1', 2, '2', 'b', 'b', null, null, , ,'null']

1 和 ‘1’不算重复,undefined, null 也要保留。不使用ES6的语法。


慕村9548890
浏览 1300回答 1
1回答

小唯快跑啊

var&nbsp;arr&nbsp;=&nbsp;[1,&nbsp;'a',&nbsp;'1',&nbsp;2,&nbsp;'2',&nbsp;'b',&nbsp;'b']; let&nbsp;resultarr&nbsp;=&nbsp;[...new&nbsp;Set(arr)];&nbsp; console.log(resultarr);//[1,&nbsp;"a",&nbsp;"1",&nbsp;2,&nbsp;"2",&nbsp;"b"]如果不去重对象的可以用下面的var&nbsp;arr&nbsp;=&nbsp;[1,&nbsp;'a',&nbsp;'1',&nbsp;2,&nbsp;'2',&nbsp;'b',&nbsp;'b',&nbsp;null,&nbsp;null,&nbsp;,&nbsp;,'null'];var&nbsp;obj&nbsp;=&nbsp;{};var&nbsp;result&nbsp;=&nbsp;[];for&nbsp;(var&nbsp;i&nbsp;=&nbsp;0;&nbsp;i&nbsp;<&nbsp;arr.length;&nbsp;i++)&nbsp;{&nbsp;&nbsp;var&nbsp;key&nbsp;=&nbsp;typeof&nbsp;arr[i]+arr[i];&nbsp;&nbsp;&nbsp;if(!obj[key]){ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;obj[key]&nbsp;=&nbsp;true; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;result.push(arr[i]) &nbsp;&nbsp;&nbsp;} }console.log(result);//或者不用多余的数组存储for&nbsp;(var&nbsp;i&nbsp;=&nbsp;0;&nbsp;i&nbsp;<&nbsp;arr.length;&nbsp;i++)&nbsp;{&nbsp;&nbsp;var&nbsp;key&nbsp;=&nbsp;typeof&nbsp;arr[i]+arr[i];&nbsp;&nbsp;&nbsp;if(!obj.hasOwnProperty(key)){ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;obj[key]&nbsp;=&nbsp;arr[i]; &nbsp;&nbsp;&nbsp;} }console.log(Object.values(obj));//es5&nbsp;for&nbsp;in遍历
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript