(Picture source network, delete, sorrry)
title
Give you an ordered array nums, ask you to delete the repeated elements in place, so that each element appears only once, return the deleted array after the new length. Instead of using extra array space, you must modify the input array in place and do so with O(1) extra space.
explain
Why is the return value an integer, but the output answer is an array? Note that the input array is passed “by reference,” which means that modifying the input array in a function is visible to the caller. You can imagine the internal operation as follows: NUMs are passed “by reference”. That is, it does not make any copies of the arguments int len = removeDuplicates(nums); Modifying the input array in a function is visible to the caller. Depending on the length returned by your function, it will print out all elements in the array within that length range.
for (int i = 0; i < len; i++) {
print(nums[i]);
}
Copy the code
example
Example 1: Input: nums = [1,2] Output: 2, nums = [1,2] Explanation: The function should return a new length of 2, and the first two elements of the original array nums are changed to 1,2. You don’t need to worry about the element after the new length in the array. Example 2: Input: nums = [0,0,1,1, 2,2,3,3,4] Output: 5, nums = [0,1,2, 2,3,4] Explanation: The function should return a new length of 5, and the first five elements of the original nums array are modified to 0,1,2,3,4. You don’t need to worry about the element after the new length in the array.
tip
0 <= nums.length <= 3 * 104-104 <= nums[I] <= 104 NUMs are sorted in ascending order
answer
function arrSplice(arr){
if(! arr.length)return 0;
let i = 0;
for(let j = 1; j < arr.length; j++){
if(arr[j] != arr[i]){
i++;
arr[i] = arr[j];
}
}
return i+1;
}
arrSplice(nums);
Copy the code