Removes duplicates from an ordered array
Here’s the code
function removeDuplicates(nums: number[]) :number {
for(let i = 0; i < nums.length - 1; i++){
if(nums[i] === nums[i+1]){
nums.splice(i, 1); i--; }}return nums.length;
};
Copy the code
- Delete duplicate elements in numS; delete duplicate elements in numS; delete duplicate elements in NUMS; The code uses the array splice method to delete duplicates directly from the original array.
- So if there are duplicates, they must be right next to each other. So you don’t need to go through twice to find duplicates. Repeat once and compare the current item to the next item.
- Nums [I +1] is the last item, so I < nums. length-1. In addition, when a duplicate element is found and deleted, the length of the original array and the corresponding value of each subscript are changed, and the subscript needs to be reset in time before comparison