本文介绍了删除重复的算法,到位和稳定(JavaScript的)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在今天的课堂上,我们被要求写一个算法。
给定一个数组,删除重复值:
- 它应该是稳定的,并且不应该使用一个内循环。
- 如果要做到位,尽可能
- 在不使用的内置函数(我只允许使用 .push )
与它搏斗了一会儿后,这是我想出了。
函数remove_dupes(ARR){ 变种看出= {}; 变种数= 0; 对于(VAR I = 0; I< arr.length - 计数;我++){ 改编[i] =改编[1 +计数]。 如果(见于[改编[I]]){ 算上++; 改编[i] =改编[1 +计数]。 一世 - ; } 看到[ARR [I] = TRUE; } arr.length = arr.length - 计数; }工作JSBin
我有一点重复code在这里,我觉得,也许是我 - 是不是最好的一段路要走。
有没有什么办法可以改善这种code(不使用内置函数)?
解决方案最后,我想我得到了你想要的东西,而无需创建一个新的数组:
函数remove_dupes(ARR){ 变种看出= {}; 变种K = 0; 对于(VAR I = 0; I< arr.length;我++){ 如果(!可见[ARR [I]){ ARR [K +] =改编[I] 看到[ARR [I] ='看见'; } } arr.length = K; } 变种X = [1,2,1,4,5,3,'道场',4,6,6,7,7,6,7,5,6,6,6,6,7,'道场', 11]; remove_dupes(X); 文件撰写(X);
希望它帮助。
In class today we were asked to write an algorithm.
Given an array, remove duplicate values:
- It should be stable, and shouldn't have to use an inner loop.
- Should be done in place, as best as possible
- No use of built in functions (I was only allowed to use .push)
After wrestling with it for a while, this is what I came up with.
function remove_dupes(arr){ var seen = {}; var count = 0; for( var i = 0; i < arr.length - count ; i++) { arr[i] = arr[i+count]; if( seen[arr[i]] ) { count++; arr[i] = arr[i+count]; i--; } seen[arr[i]] = true; } arr.length = arr.length - count; }Working JSBin
I have a bit of repeated code here and I feel that maybe the i-- isn't the best way to go.
Is there any way I could improve this code (without using built in functions)?
解决方案Finally, I think I got what you want without creating a new array:
function remove_dupes(arr){ var seen = {}; var k = 0; for( var i=0; i<arr.length ;i++) { if( !seen[arr[i]] ) { arr[k++] = arr[i]; seen[arr[i]] = 'seen'; } } arr.length = k; } var x = [ 1, 2, 1, 4, 5, 3, 'dojo', 4, 6, 6, 7, 7, 6, 7, 5, 6, 6, 6, 6, 7, 'dojo', 11 ]; remove_dupes(x); document.write(x);
Hope it helps.
更多推荐
删除重复的算法,到位和稳定(JavaScript的)
发布评论