How to efficiently remove duplicates from an array without using Set

后端 未结 30 2791
情深已故
情深已故 2020-11-22 07:29

I was asked to write my own implementation to remove duplicated values in an array. Here is what I have created. But after tests with 1,000,000 elements it took very long ti

30条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 07:50

    You can use an auxiliary array (temp) which in indexes are numbers of main array. So the time complexity will be liner and O(n). As we want to do it without using any library, we define another array (unique) to push non-duplicate elements:

    var num = [2,4,9,4,1,2,24,12,4];
    let temp = [];
    let unique = [];
    let j = 0;
    for (let i = 0; i < num.length; i++){
      if (temp[num[i]] !== 1){
        temp[num[i]] = 1;
        unique[j++] = num[i];
      }
    }
    console.log(unique);

提交回复
热议问题