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! ! ! !
The idea of removing duplicates in situ is very simple
Create a hash object with each array element as key
Each element is judged by hash whether it already exists in the array
If it exists, delete the element
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
const removeDuplicates=arr=>Array.from(new Set(arr))