javascript - js, a question that suddenly came to my mind when I was brushing leetcode
欧阳克
欧阳克 2017-06-12 09:28:19
0
3
610

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! ! ! !

欧阳克
欧阳克

温故而知新,可以为师矣。 博客:www.ouyangke.com

reply all(3)
阿神

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.

刘奇

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;
};
小葫芦

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template