Remove duplicates from Array without using Hash Table

后端 未结 7 1687
终归单人心
终归单人心 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:35

    doesn't use a hash table per se but i know behind the scenes it's an implementation of one. Nevertheless, thought I might post in case it can help. This is in JavaScript and uses an associative array to record duplicates to pass over

    function removeDuplicates(arr) {
        var results = [], dups = []; 
    
        for (var i = 0; i < arr.length; i++) {
    
            // check if not a duplicate
            if (dups[arr[i]] === undefined) {
    
                // save for next check to indicate duplicate
                dups[arr[i]] = 1; 
    
                // is unique. append to output array
                results.push(arr[i]);
            }
        }
    
        return results;
    }
    

提交回复
热议问题