Remove duplicates from Array without using Hash Table

后端 未结 7 1645
终归单人心
终归单人心 2020-12-15 14:37

i have an array which might contain duplicate elements(more than two duplicates of an element). I wonder if it\'s possible to find and remove the duplicates in the array:

相关标签:
7条回答
  • 2020-12-15 15:41

    In-place duplicate removal that preserves the existing order of the list, in quadratic time:

    for (var i = 0; i < list.length; i++) {
      for (var j = i + 1; j < list.length;) {
        if (list[i] == list[j]) {
          list.splice(j, 1);
        } else {
          j++;
        }
      }
    }
    

    The trick is to start the inner loop on i + 1 and not increment the inner counter when you remove an element.

    The code is JavaScript, splice(x, 1) removes the element at x.

    If order preservation isn't an issue, then you can do it quicker:

    list.sort();
    
    for (var i = 1; i < list.length;) {
      if (list[i] == list[i - 1]) {
        list.splice(i, 1);
      } else {
        i++;
      }
    }
    

    Which is linear, unless you count the sort, which you should, so it's of the order of the sort -- in most cases n × log(n).

    0 讨论(0)
提交回复
热议问题