删除重复的算法,到位和稳定(JavaScript的)算法、稳定、JavaScript

2023-09-11 06:05:06 作者:停电、0.1秒钟

在今天的课堂上,我们被要求写一个算法。

给定一个数组,删除重复值:

它应该是稳定的,并且不应该使用一个内循环。 如果要做到位,尽可能 在不使用的内置函数(我只允许使用 .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); 不一样的 JavaScript

希望它帮助。

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.