search

Home  >  Q&A  >  body text

javascript - js, a question that suddenly came to my mind when I was brushing leetcode

The question I was studying at that time was a question about removing duplicates from an array.
The question stem https://leetcode.com/problems...
I accepted it when I was studying it, but I suddenly thought of a question. What should I do? How can we deduplicate the original array and return the modified array without opening a new array? ?
The following is the code I passed

var removeDuplicates = function(nums) {
    if(nums === null || nums.length === 0) return 0;
    if(nums.length == 1) return 1;
    var count = 0;
    for(var i = 1 ; i < nums.length ; i++){
        if(nums[count] != nums[i]){
            count++;
            nums[count] = nums[i];
        }
    }    
    return ++count;
};

At the beginning, I thought of returning nums.length at the end, but after thinking about it carefully, I realized that this was not a joke. The original unmodified nums must be returned after writing it this way, so I started to think about how to return this modified nums. After reading the array, I still haven’t found the answer after reading a lot of articles about deduplicating arrays. Please give me some guidance! ! ! !

欧阳克欧阳克2808 days ago624

reply all(3)I'll reply

  • 阿神

    阿神2017-06-12 09:30:19

    The idea of ​​removing duplicates in situ is very simple

    1. Create a hash object with each array element as key

    2. Each element is judged by hash whether it already exists in the array

    3. If it exists, delete the element

    4. After the traversal is completed, move the array elements to fill the gaps

    Since moving array elements is a high-cost operation (for example, an N-long array is evenly dug out by N/2 empties, then the time complexity of moving elements from back to front can reach the level of N^2), and this algorithm It does not conform to the current immutable trend, so this approach is thankless and there is no need to do it in general scenarios.

    reply
    0
  • 怪我咯

    怪我咯2017-06-12 09:30:19

    This question is not a simple deduplication of an array. This array is sorted, which is different from deduplication of an out-of-order array.

    In ordered array deduplication, the same elements will be distributed together, so you only need to determine whether the next element is the same as the previous element during the traversal process to perform deduplication.

    This question was my AC at the time

    var removeDuplicates = function(nums) {
        var j = 0;
        var i = 0;
        for (; i < nums.length; i++) {
            if (nums[j] !== nums[i]) {
                nums[++j] = nums[i];
            }
        }
        return j+1;
    };

    reply
    0
  • 高洛峰

    高洛峰2017-06-12 09:30:19

    const removeDuplicates=arr=>Array.from(new Set(arr))

    reply
    0
  • Cancelreply