26. Delete duplicates from ordered arrays – LeetCode (leetcode-cn.com)

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.

Description:

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 is 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 prints out all elements in the array within that length. for (int i = 0; i < len; i++) { print(nums[i]); }Copy the code

Example 1:

Input: nums = [1,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.Copy the code

Example 2:

Input: nums = [0,0,1,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 array NUMs are modified to 0,1,2,3,4. You don't need to worry about the element after the new length in the array.Copy the code

Tip:

  • 0 <= nums.length <= 3 * 104
  • -104 <= nums[i] <= 104
  • numsThey are arranged in ascending order

=_=!! = =!! = = =!! = = =!! Return […new Set(nums)]; return […new Set(nums)]; =

AC code:

/**
 * @param {number[]} nums
 * @return {number}
 */
var removeDuplicates = function(nums) {
    let p = 0
    
    while (p < nums.length) {
        if (nums[p] === nums[p + 1]) {
            nums.splice(p, 1)
        } else {
            console.log(nums[p])
            p++
        }
    }
};
Copy the code